Python 函数统计文本文件单词出现次数并排序
以下是 Python 代码实现:
def count_words(filename):
# 读取文件
with open(filename, 'r') as f:
text = f.read()
# 将所有单词转换为小写,并去除标点符号和换行符
text = text.lower()
for char in ',.'"\n':
text = text.replace(char, ' ')
# 将文本拆分为单词列表
words = text.split()
# 统计单词出现次数
word_count = {}
for word in words:
if word in word_count:
word_count[word] += 1
else:
word_count[word] = 1
# 按照出现次数排序
sorted_words = sorted(word_count.items(), key=lambda x: x[1], reverse=True)
# 输出结果
for word, count in sorted_words:
print(word, count)
该函数接受一个文件名作为参数,读取文件并统计单词出现次数,最后按照出现次数从高到低排序输出。可以使用以下代码调用该函数:
count_words('example.txt')
其中,'example.txt'为要读取的文件名。
原文地址: https://www.cveoy.top/t/topic/nIat 著作权归作者所有。请勿转载和采集!