正如@sberry 所描述的那样,Counter 会达到目的,但如果您只搜索一个单词并且不希望获得所有单词的出现,您可以使用更简单的工具来达到目的
(我以 sberry 为例)
给定一个单词列表来查找任何给定单词的出现,可以使用列表的count方法
>>> list_of_words=['a', 'word', 'is', 'a', 'thing', 'that', 'is', 'countable']
>>> list_of_words.count('is')
2
正如您的 cmets 所显示的,您可能有兴趣在字符列表中进行搜索。比如
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