我有一个字符串列表:
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)
但是,它只返回最后一对字典,
打印(dic)
{'court': 0,
'hope': 1,
'mention': 2,
'life': 1,
'bolster': 1,
'internal': 1,
'level': 1}
最佳答案
与在示例输出中创建字典列表不同,您只创建了一个字典(并在每次检查短语时覆盖字数)。您可以使用 re.findall
来计算每个短语中的单词出现次数(如果您的任何短语包含单词后跟标点符号(例如“hope?”),这样做的好处是不会失败)。
import re
words = ['court', 'hope', 'mention', 'life', 'bolster', 'internal', 'level']
phrases = ['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']
counts = [{w: len(re.findall(r'\b{}\b'.format(w), p)) for w in words} for p in phrases]
print(counts)
# [{'court': 2, 'hope': 2, 'mention': 0, 'life': 0, 'bolster': 0, 'internal': 0, 'level': 0}, {'court': 1, 'hope': 2, 'mention': 0, 'life': 0, 'bolster': 0, 'internal': 0, 'level': 0}, {'court': 0, 'hope': 1, 'mention': 2, 'life': 1, 'bolster': 1, 'internal': 1, 'level': 1}]
关于python - 字典只返回 for 循环中的最后一个键值对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56976224/