Python 練習冊,每天一個小程序,原題來自Yixiaohan/show-me-the-code
我的代碼倉庫在Github
目標
任一個英文的純文本文件,統計其中的單詞出現的個數。
解決方案
該題目代碼如下:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
任一個英文的純文本文件,統計其中的單詞出現的個數。
"""
import re
def count_words(file_path):
with open(file_path) as file:
text = file.read()
words = re.findall(r'[a-zA-Z]+', text)
count = len(words)
return count
print(count_words('text.txt'))