【问题标题】:spacy extract entity relationships parse dep treespacy 提取实体关系解析深度树
【发布时间】: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。

【问题讨论】:

标签: python recursion nlp spacy


【解决方案1】:

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

            else:
                return get_children_ent(child)

【讨论】:

  • 我已经尝试过了,但它没有触及代码的 LOC 分支 - print(f'Loc found: {child}') return child。所以这也会导致 None。
  • 经过进一步调查,问题在于因为head.children是一个生成器,所以即使它是空的,它也永远不会是假的。您应该执行children = list(head.children) 之类的操作并检查。
  • 明白了。这就说得通了。我没有考虑到这一点。谢谢!
猜你喜欢
  • 2020-06-22
  • 2022-08-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-27
  • 2016-03-01
  • 2015-04-24
相关资源
最近更新 更多