[英]5 most common words in text file python
我有这段代码可以在文本文件中搜索5个最常用的单词,但是我不能在程序末尾使用排序和反向功能...我将如何避免使用它们?
words = open('romeo.txt').read().lower().split()
uniques = []
for word in words:
if word not in uniques:
uniques.append(word)
counts = []
for unique in uniques:
count = 0
for word in words:
if word == unique:
count += 1
counts.append((count, unique))
counts.sort()
counts.reverse()
for i in range(min(5, len(counts))):
count, word = counts[i]
print('%s %d' % (word, count))
from collections import Counter
c = Counter(words)
c.most_common(5)
使用sorted()
函数并将结果保存在变量中,然后将其反转,如下所示:
counts = sorted(counts, reverse=True)
该行代码将对列表进行排序并为您反向,并将结果保存为计数。 然后,您可以根据需要使用计数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.