我正在尝试获取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)发布于 2017-08-22 17:28:47
实际上,我建议您继续使用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秒。
您的代码有点杂乱无章--看起来您已经尝试将几种方法结合在一起,将每一种方法都保存在这里和那里。我的代码已经用一些解释函数进行了注释。希望这应该是相对简单的,但如果你仍然对任何事情感到困惑,请告诉我。
发布于 2017-08-22 16:39:27
您还没有从.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]https://stackoverflow.com/questions/45822827
复制相似问题