【发布时间】:2022-01-24 01:01:41
【问题描述】:
我正在尝试从文本中提取实体及其关系。我正在尝试使用实体提取来解析依赖树以执行该操作。递归函数逻辑一定有问题,导致我无法解析该信息,但我没有看到它是什么。我想使用依赖树+实体来形成(人,动作,位置)提取。
期望的输出:人物:Lou Pinella,动作:退出,地点:体育场
代码示例:
import spacy
from spacy import displacy
nlp = spacy.load('en_core_web_lg')
doc = nlp("Lou Pinella exited from the far left side of the Stadium.")
def get_children_ent(head):
if head.children:
for child in head.children:
if child.ent_type_ == "LOC":
print(f'Loc found: {child}') # it is hitting this branch
return child
else:
return get_children_ent(child)
else:
return "No Children"
for ent in doc.ents:
print(ent.text, ent.label_)
if ent.label_ == "PERSON":
person = ent.text
head = ent.root.head
loc = get_children_ent(head)
print(f'Person: {person}')
print(f'Head: {head}')
print(f'Person: {person}, action:{head}, Loc:{loc}')
displacy.render(doc, options={"fine_grained": True})
打印语句 - 你可以看到它正在点击位置逻辑并打印它,但在递归函数中返回仍然是 None。
Lou Pinella PERSON
Loc found: Stadium
Person: Lou Pinella
Head: exited
Person: Lou Pinella, action:exited, Loc:None
Stadium LOC
已编辑:将 return get_child_ent(child) 添加到 else。
【问题讨论】:
-
你应该看看 DependencyMatcher。 spacy.io/usage/rule-based-matching#dependencymatcher
-
谢谢。我会看看那个。
标签: python recursion nlp spacy