【发布时间】:2016-08-12 15:20:01
【问题描述】:
我正在尝试编写一个 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。我应该在我的代码中进行哪些更改才能发生这种情况?
【问题讨论】:
-
使用字典或集合。 dict 在这里更有意义,但是为集合重写代码会少一些工作。
标签: python python-2.7