我正在尝试获取 txt 文件中 10 个最常用单词的列表,最终目标是构建词云。当我打印时,以下代码不会产生任何结果。
>>> import collections
>>> from collections import Counter
>>> file = open('/Users/Desktop/word_cloud/98-0.txt')
>>> wordcount={}
>>> d = collections.Counter(wordcount)
>>> for word, count in d.most_common(10):
print(word, ": ", count)
其实我建议你继续使用
Counter
。它是一个非常有用的工具,用于计算事物,但它具有非常富有表现力的语法,因此您无需担心 sort
任何事情。使用它,您可以:
from collections import Counter
#opens the file. the with statement here will automatically close it afterwards.
with open("input.txt") as input_file:
#build a counter from each word in the file
count = Counter(word for line in input_file
for word in line.split())
print(count.most_common(10))
使用我的
input.txt
,其输出为
[('THE', 27643), ('AND', 26728), ('I', 20681), ('TO', 19198), ('OF', 18173), ('A', 14613), ('YOU', 13649), ('MY', 12480), ('THAT', 11121), ('IN', 10967)]
我对它做了一些更改,这样它就不必将整个文件读入内存。我的
input.txt
是莎士比亚作品的无标点版本,以证明这段代码是快。在我的机器上大约需要 0.2 秒。
您的代码有点随意 - 看起来您已经尝试将几种方法结合在一起,并在这里和那里保留每种方法的一些部分。我的代码已用一些解释性函数进行了注释。希望它应该相对简单,但如果您仍然对任何事情感到困惑,请告诉我。
您还没有从 .txt 文件中提取任何内容。文本文件的内部是什么样的?如果您想将单词分类为由空格分隔的字符组,您可以使用以下命令获取单词列表:
with open('path/to/file.txt', 'r') as f:
words = ' '.split(f.read())
然后获取 10 个最常见的方法(可能有更有效的方法,但这是我首先发现的):
word_counter = {}
for word in words:
if word in word_counter:
word_counter[word] += 1
else:
word_counter[word] = 1
popular_words = sorted(word_counter, key = word_counter.get, reverse = True)
print popular_words[:10]