Python 书籍(.txt文件)中按频率排序的单词
我正在使用:Python 书籍(.txt文件)中按频率排序的单词,python,frequency,words,word-frequency,Python,Frequency,Words,Word Frequency,我正在使用: from collections import Counter wordlist = open('mybook.txt','r').read().split() c = Counter(wordlist) print c # result : # Counter({'the': 9530, 'to': 5004, 'a': 4203, 'and': 4202, 'was': 4197, 'of': 3912, 'I': 2852, 'that': 2574, ... }) 打印
from collections import Counter
wordlist = open('mybook.txt','r').read().split()
c = Counter(wordlist)
print c
# result :
# Counter({'the': 9530, 'to': 5004, 'a': 4203, 'and': 4202, 'was': 4197, 'of': 3912, 'I': 2852, 'that': 2574, ... })
打印一本书的所有单词,按频率排序
如何将此结果写入.txt输出文件?
g = open('wordfreq.txt','w')
g.write(c) # here it fails
下面是所需的输出wordfreq.txt
:
第9530页至,5004
a、 5004
和,4203
是,4197
我想这可能是你需要的帮助:如何按你要求的格式打印字典。前四行是您的原始代码
from collections import Counter
wordlist = open('so.py', 'r').read().split()
c = Counter(wordlist)
print c
outfile = open('output.txt', 'w')
for word, count in c.items():
outline = word + ',' + str(count) + '\n'
outfile.write(outline)
如果你想以一种有序的方式写它,你可以这样做
from collections import Counter
wordlist = open('so.py', 'r').read().split()
word_counts = Counter(wordlist)
write_file = open('wordfreq.txt', 'w')
for w, c in sorted(word_counts.iteritems(), key=lambda x: x[1], reverse=True):
write_file.write('{w}, {c}\n'.format(w=w, c=c))
我认为这可以做得更简单一些。我还使用了一个上下文管理器(
with
)来自动关闭文件
from collections import Counter
with open('mybook.txt', 'r') as mybook:
wordcounts = Counter(mybook.read().split())
with open('wordfreq.txt', 'w') as write_file:
for item in word_counts.most_common():
print('{}, {}'.format(*item), file=write_file)
如果文件特别大,可以使用
wordcounts = Counter(x for line in mybook for x in line.split())
你想做什么?你做过什么调查吗?我希望没有人回答这个问题,让你真正尝试一些东西。所以这不是一个让别人免费为你编码的地方。你需要先尝试一下,研究一下如何做某事。@JohnRuddell如果你不想回答,那就别做。我尝试了各种方法,包括尝试
json.dumps
dict,然后意识到它不仅是dict
,而且是一件更复杂的事情。。。好吧,再说一遍,如果你不喜欢这个问题,那就不要回答,但我看不出你的评论有什么意义。@Basj有几件事,首先我没有否决你的问题。。但是其他人有,因为你的问题没有试图解决这个问题。如果您尝试过各种方法,请将它们张贴在您的问题中。我们可以告诉你哪里出了问题。。。。最重要的是,我可以做一个简单的谷歌搜索,很容易找到解决方案。提问前缺乏研究通常会让你投很多反对票。你的确切问题是如何将结果写入.txt输出文件?
在谷歌搜索中。谷歌搜索有多难?如果你尝试,答案就在那里。记住谷歌是你的朋友。“不要直接求助于此。”约翰鲁德尔谢谢你的回答。我认为用json.dumps
粘贴我失败的尝试会让问题变得混乱,并降低未来的可读性。好吧,我不会再补充了,如果没有人想回答,就这样,句号。我想这会很有趣。你说不行,那就随它去吧。谢谢!只是一件小事:如何按频率(count
)排序?在打印c中,它被神奇地排序了!(我检查了三倍)实际的答案是在线搜索“按值排序python字典”。在你发表评论之前,你怎么没有发现什么?