如何使用字典计算单词在列表中的出现次数

2024-05-29 00:22:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一张单子

words = ['two', 'forks.', 'one', 'knife.', 'two', 'glasses.','one', 
'plate.', 'one', 'naptkin.', 'his,' 'glasses.', 'his', 'knife.']

需要用这样的字典计算单词的出现次数。你知道吗

word_counts = {'two':2, 'one':3, 'forks.':1, 'knife.':2, \
           'glasses.':2, 'plate.':1, 'naptkin.':1, 'his':2}

我该怎么做呢?谢谢你的帮助!你知道吗


Tags: 字典单词次数oneword单子wordstwo
3条回答
words = ['two', 'forks.', 'one', 'knife.', 'two', 'glasses.','one',
'plate.', 'one', 'naptkin.', 'his,' 'glasses.', 'his', 'knife.']

d = {}
for w in words:
    if w in d.keys():
        d[w] += 1
    else:
        d[w] = 1

print(d)

第一种方法类似于Francky V的方法,但使用.setdefault()方法。例如:

>>> d = {}
>>> d.setdefault('two', 0) # 'two' is not in d, we can set it 
0
>>> d.setdefault('two', 1000)  # 'two' is now in d, we cannot set it, returns current value
0

所以,解决方案是:

d = {}
for word in words:
    d.setdefault(word, 0)
    d[word] += 1

第二种解决方案利用collections.defaultdict

import collections
d = collections.defaultdict(int)
for word in words:
    d[word] += 1

这是因为d是值为defaultdictint。我们第一次提到d[word]时,该值会自动设置为0。你知道吗

当然,collections.Counter是最好的解决方案,因为该类是为此目的构建的。你知道吗

from collections import Counter
words = ['two', 'forks.', 'one', 'knife.', 'two', 'glasses.','one', 'plate.', 'one', 'naptkin.', 'his,' 'glasses.', 'his', 'knife.']
dict(Counter(words))

相关问题 更多 >

    热门问题