Python统计文本文件单词出现次数并排序
以下是Python代码实现:/n/npython/nimport re/n/n# 读取文本文件/nwith open('text.txt', 'r') as f:/n text = f.read()/n/n# 将文本中的标点符号和换行符替换为空格/ntext = re.sub(r'[^/w/s]', ' ', text)/ntext = re.sub(r'//s+', ' ', text)/n/n# 将文本分割成单词列表/nwords = text.split()/n/n# 统计每个单词出现的次数/nword_count = {}/nfor word in words:/n if word in word_count:/n word_count[word] += 1/n else:/n word_count[word] = 1/n/n# 按照出现次数从高到低排序输出/nfor word, count in sorted(word_count.items(), key=lambda x: x[1], reverse=True):/n print(word, count)/n/n/n假设文本文件名为text.txt,程序首先读取文本文件并将其存储在变量text中。接下来,使用正则表达式将文本中的标点符号和换行符替换为空格,并将连续的空格替换为单个空格,得到一个单词列表。然后,使用一个字典word_count统计每个单词出现的次数。最后,使用Python的sorted()函数,按照出现次数从高到低排序输出每个单词及其出现次数。
原文地址: https://www.cveoy.top/t/topic/nIal 著作权归作者所有。请勿转载和采集!