我正在尝试编写一个python代码来计算文本文件中每个单词的频率。代码应该为每个唯一的单词显示一行。我写的代码显示重复的单词。你知道吗
import string
text = open('mary.txt','r')
textr = text.read()
for punc in string.punctuation:
textr = textr.replace(punc, "")
wordlist = textr.split()
for word in wordlist:
count = wordlist.count(word)
print word,':',count
我的电流输出是。。。你知道吗
are : 1
around : 1
as : 1
at : 2
at : 2
away : 1
back : 1
be : 2
be : 2
because : 1
below : 1
between : 1
both : 1
but : 1
by : 2
by : 2
输出应该只显示at : 2
、be : 2
和by : 2
一次。我应该在我的代码中做些什么来实现这一点?你知道吗
作为实现这一点的另一种方法,您可以采用您的解决方案,将所有条目作为(word,count)元组添加到一个集合中,然后打印该集合。您可能应该像@smarx指出的那样重新考虑您的实现,但这将使用您的本机代码解决问题。你知道吗
代码的问题是,您正在创建一个包含所有单词的列表,然后循环使用它们。您希望创建某种只存储唯一单词的数据结构。一个
dict
是一个很好的方法,但是在Python中有一个专门的集合叫做Counter
,它就是为了这个目的而构建的。你知道吗尝试一下(未经测试):
您可以尝试以下方法:
相关问题 更多 >
编程相关推荐