我有一个字符串列表:
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}
与在示例输出中创建dict列表不同,您只创建了一个dict(每次检查一个短语时都会覆盖单词)。您可以使用
re.findall
来计算每个短语中的单词出现次数(如果您的任何短语包含后跟标点符号(如“hope?”)的单词,这样做的好处是不会失败)。你知道吗试试这个
输出:
两个问题:您在错误的位置初始化了
dic
,而没有在列表中收集这些dic
。解决方法如下:相关问题 更多 >
编程相关推荐