@sberryが示したように、カウンターは目的を果たしますが、単一の単語を1回だけ検索し、すべての単語の出現を取得することに興味がない場合は、目的のためにより単純なツールを使用できます
(私はsberryから例を取りました)
与えられた単語の出現を見つけるための単語のリストが与えられた場合、リストのcount
メソッドを使用できます
>>> list_of_words=['a', 'word', 'is', 'a', 'thing', 'that', 'is', 'countable']
>>> list_of_words.count('is')
2
あなたのコメントが示しているように、文字のリストを検索することに興味があるかもしれません。そのような
letters =
['i', 'n', 'e', 'e', 'd', 's', 'o', 'm', 'e', 'h', 'e', 'l', 'p', 'h', 'e', 'l', 'p', 'm', 'e', 'p', 'l', 'e', 'a', 's', 'e', 'I', 'n', 'e', 'e', 'd', 'h', 'e', 'l', 'p']
すべての文字を連結して生成された後の文字列でカウントを使用することもできます
>>> ''.join(letters).count('help')
3
言葉がごちゃごちゃにcollections.Counter
なったらここで魔法をかけて
>>> def count_words_in_jumbled(jumbled,word):
jumbled_counter = collections.Counter(jumbled)
word_counter = collections.Counter(word)
return min(v /word_counter[k] for k,v in jumbled_counter.iteritems() if k in word)
>>> count_words_in_jumbled(['h','e','l','l','h','e','l','l','h','e','l'],'hel')
3
>>> count_words_in_jumbled(['h','e','l','l','h','e','l','l','h','e','l'],'hell')
2
>>> count_words_in_jumbled(['h','x','e','y','l','u','p'] ,'help')
1