[英]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.