用于collections.Counter
计算单词和open()用于打开文件:
from collections import Counter
def main():
#use open() for opening file.
#Always use `with` statement as it'll automatically close the file for you.
with open(r'C:\Data\test.txt') as f:
#create a list of all words fetched from the file using a list comprehension
words = [word for line in f for word in line.split()]
print "The total word count is:", len(words)
#now use collections.Counter
c = Counter(words)
for word, count in c.most_common():
print word, count
main()
collections.Counter
例子:
>>> from collections import Counter
>>> c = Counter('aaaaabbbdddeeegggg')
Counter.most_common根据计数按排序顺序返回单词:
>>> for word, count in c.most_common():
... print word,count
...
a 5
g 4
b 3
e 3
d 3