spacy 提取实体关系解析 dep 树

spacy extract entity relationships parse dep tree

我正在尝试从文本中提取实体及其关系。我正在尝试通过实体提取来解析依赖树以执行该操作。递归函数逻辑一定有问题,导致我无法解析该信息,但我没有看到它是什么。我想用依赖树+实体组成一个(person,action,location)抽取

期望输出:人物:Lou Pinella,action:exited,Loc:Stadium

代码示例:

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})

打印语句 - 您可以看到它正在命中位置逻辑并打印它,但是 return 在递归函数中仍然是 None。

Lou Pinella PERSON
Loc found: Stadium
Person: Lou Pinella
Head: exited
Person: Lou Pinella, action:exited, Loc:None
Stadium LOC

EDITED: 添加 return get_child_ent(child) 到 else.

您的递归调用没有返回值。你需要这个:

            else:
                return get_children_ent(child)