Python 统计文本文件单词出现次数并排序
以下是 Python 代码实现:
def count_words(filename):
# 打开文件并读取内容
with open(filename, 'r') as f:
text = f.read()
# 将文本中的所有单词转换成小写并存入列表中
words = text.lower().split()
# 统计每个单词出现的次数并存入字典中
word_count = {}
for word in words:
if word in word_count:
word_count[word] += 1
else:
word_count[word] = 1
# 将字典按照出现次数从高到低排序并输出结果
sorted_word_count = sorted(word_count.items(), key=lambda x: x[1], reverse=True)
for word, count in sorted_word_count:
print(word, count)
该函数接受一个文本文件的路径作为参数,读取文件内容并统计单词出现次数。最后按照出现次数从高到低排序输出。可以通过以下代码调用该函数:
count_words('example.txt')
原文地址: https://www.cveoy.top/t/topic/nIaq 著作权归作者所有。请勿转载和采集!