2013-03-20 65 views
0

任何人都可以告诉我如何统计单词出现在字典中的次数。我已经将一个文件读入终端列表中。我是否需要将列表放入字典中,或者开始将文件读入终端中的字典而不是列表中?该文件是一个日志文件,如果重要...在Python中计数单词

+0

请更精确。你能举一个例子,你的名单如何看起来像原则? – flonk 2013-03-20 12:54:53

回答

4

你应该看看collections.Counter。你的问题有点不清楚。

0

collections.Counter有它。

给出的例子有符合您的要求我想

from collections import Counter 
import re 
words = re.findall(r'\w+', open('log file here.txt').read().lower()) 
cont = Counter(words) 
#to get the count of required_word 
print cont['required_word'] 
1

短的例子:

from collections import Counter 

s = 'red blue red green blue blue' 

Counter(s.split()) 
> Counter({'blue': 3, 'red': 2, 'green': 1}) 

Counter(s.split()).most_common(2) 
> [('blue', 3), ('red', 2)]