如何在Python中计算单词词典



我有一个关于Python中字典处理的问题。

我想知道如何将字典与单词表进行比较。

[我的输入示例]

text = ['fall', 'big', 'pocket', 'layer', 'park', ...]
mylist = ['spring', 'summer', 'fall', 'winter', 'school', ...]

[制作字典代码]

lst_dic = {mylist : 0 for mylist in mylist }
lst_dic

我想知道mylisttext中有多少单词匹配。

[故障代码]

lst_dic = {}
for w in mylist:
if w in text_1_1:
lst_dic[w] += 1
else:
lst_dic[w] = 0

因此,我想知道字典的关键字和值。像这样:

{ 'spring':0,
'summer':3,
'fall':1,
'winter':0,
...
}

然后,我想提取超过10个计数值的属性。

请看一下这个问题。

如果第一次在mylist中出现关键字(单词(,您的代码没有正确初始化lst_dic。因此,您得到一个KeyError

请改用collections.defaultdict初始化字典。这允许您从代码中删除else分支,并且只需在每次遇到text中某个单词的频率时递增。

import collections
text = ['fall', 'big', 'pocket', 'layer', 'park']
mylist = ['spring', 'summer', 'fall', 'winter', 'school']
lst_dic = collections.defaultdict(int)
for w in mylist:
if w in text:
lst_dic[w] += 1
# Show the counts of all `text` words occurring in `mylist`:
print(dict(lst_dic))
# Extract those with counts > 10:
print([e for e in lst_dic if lst_dic[e] > 10])
# Or, if you want it as a dictionary:
print({e: lst_dic[e] for e in lst_dic if lst_dic[e] > 10})

假设一个defaultdictlst_dic。现在,将字典key与文本进行比较。如果匹配则CCD_ 12。如果值大于10,现在提取最终字典。

from collections import defaultdict
text = ['fall', 'big', 'pocket', 'layer', 'park']
mylist = ['spring', 'summer', 'fall', 'winter', 'school']
lst_dic = defaultdict(int)
for w in mylist:
if w in text:
lst_dic[w] += 1
result = {key: value for key, value in lst_dic.items() if value > 10}
print(result)

为了避免使用许多循环,我更喜欢采用这种方法:

1-使用Counter((计算文本中的所有单词。

from collections import Counter
text_count = dict(Counter(text))

2-创建一个空字典mylist_count,遍历mylist,将其与text_count键匹配,并设置mylist_coount值。

mylist_count = dict()
for el in mylist:
try:
mylist_count[el] = text_count[el]
except:
mylist_count[el]=0

最新更新