Python 代码示例:统计文本文件单词出现频率
本示例使用 Python 代码读取文本文件,并统计其中所有单词的出现频率,并按照频率降序输出。
import re
from collections import Counter
# 读取文本文件
with open('input.txt', 'r') as f:
text = f.read()
# 提取单词并计算出现次数
words = re.findall('\w+', text.lower())
word_counts = Counter(words)
# 输出结果
for word, count in word_counts.most_common():
print(word, count)
请确保将'input.txt'替换为实际文件名,并且安装了必要的Python库。
原文地址: http://www.cveoy.top/t/topic/lMty 著作权归作者所有。请勿转载和采集!