2013-03-20 70 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)]