任何单词在字符串中出现的次数.单词中的每个字母大小写(大写或小写)都很重要.输出中的行可以按任意顺序排列



任何单词在字符串中出现的次数。单词中的每个字母大小写(大写或小写)都很重要。输出中的行可以按任意顺序排列:

我们尝试了

列表,我们尝试了字典,我们也尝试了禅

我试过这个:

sequence_of_sentences = ['We tried list and we tried dicts also we tried Zen']
from collections import Counter
counts = Counter()
for sentence in sequence_of_sentences:
    counts.update(word.strip('.,?!"'') for word in sentence.split())
print(counts)

但是我怎么能像这样列出它们:

and 1
We 1
tried 3
dicts 1
list 1
we 2
also 1
Zen 1
>>> for key,value in counts.items():
...     print(key,value)
...
dicts 1
also 1
list 1
Zen 1
and 1
We 1
we 2
tried 3
集合

。计数器dict subclass用于计算存储元素的可哈希对象作为键并计为它们的值。因此,您可以应用字典的所有功能:

for key,value in counts.items():
    print(key,value)

你也可以使用collections.defaultdict,它比计数器快。

>>> my_dict = collections.defaultdict(int)
>>> a
'We tried list and we tried dicts also we tried Zen' 
>>> for x in a.split():
...     my_dict[x] +=1
... 
>>> my_dict
defaultdict(<class 'int'>, {'list': 1, 'We': 1, 'Zen': 1, 'tried': 3, 'also': 1, 'dicts': 1, 'we': 2, 'and': 1})

最新更新