我有一个字符串列表,如下:
A = [
'philadelphia court excessive disappointed court hope hope',
'hope hope jurisdiction obscures acquittal court',
'mention hope maryland signal held mention problem internal reform life bolster level grievance'
]
还有另一个列表如下:
B = ['court', 'hope', 'mention', 'life', 'bolster', 'internal', 'level']
我想基于字符串列表 A
中单词列表 B
的出现次数创建字典。就像这样:
C = [
{'count':2,'hope':2,'mention':0,'life':0,'bolster':0,'internal':0,'level':0},
{'count':1,'hope':2,'mention':0,'life':0,'bolster':0,'internal':0,'level':0},
{'count':0,'hope':1,'mention':2,'life':1,'bolster':1,'internal':1,'level':1}
]
我喜欢的是,
dic={}
for i in A:
t=i.split()
for j in B:
dic[j]=t.count(j)
但是,它只返回字典的最后一对键值对。
print(dic)
{'court': 0,
'hope': 1,
'mention': 2,
'life': 1,
'bolster': 1,
'internal': 1,
'level': 1}
dic
。请检查我的答案。 - FatihAkicicollections.Counter
来代替手动计数,从而稍微改进你的代码。 - Blckknght