我需要在一个文本文件中显示 10 个最常用的单词,从最频繁到最少以及它被使用的次数。我不能使用字典或计数器功能。到目前为止我有这个:
import urllib
cnt = 0
i=0
txtFile = urllib.urlopen("http://textfiles.com/etext/FICTION/alice30.txt")
uniques = []
for line in txtFile:
words = line.split()
for word in words:
if word not in uniques:
uniques.append(word)
for word in words:
while i<len(uniques):
i+=1
if word in uniques:
cnt += 1
print cnt
现在我想我应该查找数组“uniques”中的每个单词,看看它在这个文件中重复了多少次,然后将其添加到另一个计算每个单词实例的数组中。但这就是我被困的地方。我不知道如何进行。
任何帮助,将不胜感激。谢谢
原文由 KevinKZ 发布,翻译遵循 CC BY-SA 4.0 许可协议
上述问题可以通过使用下面的 python 集合轻松解决。