按频率排序
这个问题在这里已经有了答案:
你必须在这里使用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
作为变量名称。
使用collections.Counter来帮助计算事物,并with
语句来帮助打开(和关闭)文件。
import collections
with open('C:TempTest2.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))
看看collections.Counter
>>> wordlist = ['foo', 'bar', 'foo', 'baz']
>>> import collections
>>> counter = collections.Counter(wordlist)
>>> counter.most_common()
[('foo', 2), ('baz', 1), ('bar', 1)]
链接地址: http://www.djcxy.com/p/18157.html