python - 基于规则的 Spacy 实体匹配器

标签 python information-extraction spacy

我想使用 python 库 spacy 来匹配文本中的标记(添加标签作为语义引用)。然后,我想使用匹配来提取标记之间的关系。我的第一个方法是利用 spacy 的 matcher.addmatcher.add_patternmatcher.add 工作正常,我可以找到 token ,到目前为止我的代码:

import spacy


nlp = spacy.load('en')

def merge_phrases(matcher, doc, i, matches):
    if i != len(matches)-1:
        return None
    spans = [(ent_id, label, doc[start : end]) for ent_id, label, start, end in matches]
    for ent_id, label, span in spans:
        span.merge('NNP' if label else span.root.tag_, span.text, nlp.vocab.strings[label])



matcher = spacy.matcher.Matcher(nlp.vocab)



matcher.add(entity_key='1', label='FINANCE', attrs={}, specs=[[{spacy.attrs.ORTH: 'financial'}, {spacy.attrs.ORTH: 'instrument'}]], on_match=merge_phrases)
matcher.add(entity_key='2', label='BUYER', attrs={}, specs=[[{spacy.attrs.ORTH: 'acquirer'}]], on_match=merge_phrases)
matcher.add(entity_key='3', label='CODE', attrs={}, specs=[[{spacy.attrs.ORTH: 'Code'}]], on_match=merge_phrases)

这工作正常并且输出非常好的结果:

doc = nlp(u'Code used to identify the acquirer of the financial instrument.')

# Output
['Code|CODE', 'used|', 'to|', 'identify|', 'the|', 'acquirer|BUYER', 'of|', 'the|', 'financial instrument|FINANCE', '.|']

我的问题是,如何使用 matcher.add_patern 来匹配标记之间的关系,例如

matcher.add_pattern("IS_OF", [{BUYER}, {'of'}, {FINANCE}])

对于输出:

doc = nlp(u'Code used to identify the acquirer of the financial instrument.')

# Output
[acquirer of financial instrument]

我尝试了不同的方法来使其工作,但显然不行,我猜我对 matcher.add_pattern 的理解有问题。

  1. 请告诉我如何做到这一点的正确方向 空间大?
  2. 是否可以在此处添加正则表达式来查找模式,如何实现?
  3. 如何添加多个具有相同标签的标记,或以某种方式创建 同一标签的标记列表,例如。 “金融”?

我将不胜感激任何评论。

最佳答案

您的匹配器将识别标记,但要找到它们之间的关系,您必须进行依赖项解析。 这是visual example from spacy :

enter image description here

然后您可以遍历树来查找标记之间的关系。 https://spacy.io/docs/usage/dependency-parse#navigating

每个标记的 dep(枚举)和 dep_(详细名称)属性将为您提供与其子标记的关系

关于python - 基于规则的 Spacy 实体匹配器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43397502/

相关文章:

python - 将文本分成句子 NLTK 与 spaCy

python - ndb.get_multi() 返回空实体

python - 从 IP 地址确定 AWS 区域?

nlp - 维基距离 : distance between Wiki topics and categories?

parsing - 如何利用机器学习提取公司债券信息

python - 带有缩写的spacy分割句子

python - 如何在 Python 中从 XML/SOAP 中提取数据

python - 使用 Python 生成文件创建日期和最后修改日期

information-retrieval - IR评估中如何衡量ranking、AP、MAP、recall的一些想法和方向

python - 从源代码安装时,使用 Python 3 和 Windows 安装 Spacy for NLP 会出现错误