问题描述
list_dicts = [{'id': 1,'text': 'hello my name is Carla'},{'id': 2,'text': 'hello my name is John' }]
我将Spacy命名实体识别应用于嵌套文本,如下所示:
for d in list_dicts:
for k,v in d.items():
if k=='text':
doc = nlp(v)
for ent in doc.ents:
print([ent.text,ent.label_])
['Bob','PERSON']
['John','PERSON']
我想将命名实体添加到每个嵌套字典的相应文本中,如下所示:
list_dicts = [{'id': 1,'text': 'hello our names are Carla and Bob','entities':[['Carla','PERSON'],['Bob':'PERSON']]},'text': 'hello my name is John','entities': [['John','PERSON']] }]
就目前而言,我尝试实现zip()作为将实体链接到原始文本的方法,然后将它们转换为新的词典列表,但是zip()似乎不适用于Spacy对象。
解决方法
使用dict.setdefault
例如:
for d in list_dicts:
doc = nlp(d['text'])
for ent in doc.ents:
d.setdefault('entities',[]).append([ent.text,ent.label_])