很简单,您只需要在文件中找到 5 个最常用的单词。
所以你可以做这样的事情:
wordcount = sorted(wordcount.items(), key=lambda x: x[1], reverse=True)
然后,这个字典将按值排序(记住sorted
返回一个列表)。
您可以使用以下代码获取 5 个最常用的单词:
for k, v in wordcount[:5]):
print (k, v)
所以完整的代码如下:
wordcount = {}
with open('alice.txt') as file: # with can auto close the file
for word in file.read().split():
if word not in wordcount:
wordcount[word] = 1
else:
wordcount[word] += 1
wordcount = sorted(wordcount.items(), key=lambda x: x[1], reverse=True)
for k, v in wordcount[:5]:
print(k, v)
此外,这是一种更简单的方法来使用 use collections.Counter
:
from collections import Counter
with open('alice.txt') as file: # with can auto close the file
wordcount = Counter(file.read().split())
for k, v in wordcount.most_common(5):
print(k, v)
输出与第一个解决方案相同。