python英文单词统计代码
时间: 2023-10-13 14:19:59 浏览: 47
以下是Python代码,用于对文本文件中的英文单词进行统计:
```python
import re
from collections import Counter
def count_words(filepath):
with open(filepath, 'r') as file:
# 读取文件内容
text = file.read()
# 使用正则表达式找到所有英文单词
words = re.findall(r'\b\w+\b', text)
# 统计单词数量
word_count = Counter(words)
# 输出结果
print("Total words:", len(words))
print("Unique words:", len(word_count))
print("Top 10 words:")
for word, count in word_count.most_common(10):
print(word, count)
if __name__ == '__main__':
count_words("example.txt")
```
这段代码会打开一个名为“example.txt”的文本文件,并对其中的英文单词进行统计。它使用正则表达式来找到所有单词,然后使用Python的Counter类来统计每个单词的数量。最后,它会输出总单词数、不同单词数和出现次数最多的前10个单词。