假设需要单独查找单词(即您要按str.split()制作的单词计数):
编辑:正如 cmets 中所建议的,此处计数器是一个不错的选择:
from collections import Counter
def count_many(needles, haystack):
count = Counter(haystack.split())
return {key: count[key] for key in count if key in needles}
运行如下:
count_many(["foo", "bar", "baz"], "testing somefoothing foo bar baz bax foo foo foo bar bar test bar test")
{'baz': 1, 'foo': 4, 'bar': 4}
请注意,在 Python return dict((key, count[key]) for key in count if key in needles)。
当然,另一种选择是简单地返回整个 Counter 对象,并仅在需要时获取所需的值,因为根据情况,拥有额外的值可能不是问题。
旧答案:
from collections import defaultdict
def count_many(needles, haystack):
count = defaultdict(int)
for word in haystack.split():
if word in needles:
count[word] += 1
return count
结果:
count_many(["foo", "bar", "baz"], "testing somefoothing foo bar baz bax foo foo foo bar bar test bar test")
defaultdict(<class 'int'>, {'baz': 1, 'foo': 4, 'bar': 4})
如果您非常反对返回 defaultdict(您不应该这样做,因为它在访问时的功能与 dict 完全相同),那么您可以使用 return dict(count) 来获取普通字典。