0

ある単語が辞書に登場する回数を数える方法を誰か教えてください。Iv はすでにファイルを端末に読み込み、リストに入れています。リストを辞書に入れるか、ファイルをターミナルに読み込んで、リストではなく辞書に入れる必要がありますか? それが重要な場合、ファイルはログファイルです...

4

3 に答える 3

4

を調べる必要がありますcollections.Counter。あなたの質問は少し不明確です。

于 2013-03-20T12:51:49.173 に答える
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)]
于 2013-03-20T13:06:36.393 に答える
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']
于 2013-03-20T13:00:51.130 に答える