3 回答
TA贡献1788条经验 获得超4个赞
您必须在word_freq.items()这里使用:
lis = sorted(word_freq.items(), key = lambda x:x[1], reverse = True)
for word,freq in lis:
print ("%-10s %d" % (word, freq))
不要list用作变量名。
TA贡献1876条经验 获得超5个赞
使用collections.Counter有助于对事物进行计数,并使用withstatement来帮助打开(和关闭)文件。
import collections
with open('C:\\Temp\\Test2.txt', 'r') as f:
text = f.read()
word_freq = collections.Counter(text.lower().split())
for word, freq in word_freq.most_common():
print ("%-10s %d" % (word, freq))
TA贡献1951条经验 获得超3个赞
看一下集合。
>>> wordlist = ['foo', 'bar', 'foo', 'baz']
>>> import collections
>>> counter = collections.Counter(wordlist)
>>> counter.most_common()
[('foo', 2), ('baz', 1), ('bar', 1)]
添加回答
举报