首页 > 解决方案 > 具有 SpaCy 的自定义实体标尺未返回匹配项

问题描述

链接显示如何创建自定义实体标尺。

我基本上复制并修改了另一个自定义实体标尺的代码,并使用它在 a 中查找匹配项,doc如下所示:

nlp = spacy.load('en_core_web_lg')
ruler = EntityRuler(nlp)

grades = ["Level 1", "Level 2", "Level 3", "Level 4"]
for item in grades:
    ruler.add_patterns([{"label": "LEVEL", "pattern": item}])

nlp.add_pipe(ruler)

doc = nlp('Level 2 employee first 12 months 1032.70')

with doc.retokenize() as retokenizer:
    for ent in doc.ents:
        retokenizer.merge(doc[ent.start:ent.end])

matcher = Matcher(nlp.vocab)
pattern =[{'ENT_TYPE': {'REGEX': 'LEVEL'}}, {'ORTH': 'employee'}]
matcher.add('PAY_LEVEL', None, pattern)
matches = matcher(doc)

for match_id, start, end in matches:
    span = doc[start:end]
    print(span)

但是,当我运行代码(在 Jupyter 笔记本中)时,没有返回任何内容。

你能告诉我:

  1. 如果代码什么也没返回,是否意味着没有找到匹配项?

  2. 为什么我的代码找不到匹配项,尽管它与原始代码几乎相同(除了添加到标尺的模式)?我做错了什么?

谢谢你。

标签: pythonspacy

解决方案


问题是英文模型中提供的 NER 组件与您的 EntityRuler 组件之间的交互。NER 组件查找2为数字 ( CARDINAL) 并且存在实体不允许重叠的限制,因此 EntityRuler 组件找不到任何匹配项。

您可以在 NER 组件之前添加 EntityRuler:

nlp.add_pipe(ruler, before='ner')

或者告诉 EntityRuler 允许覆盖现有实体:

ruler = EntityRuler(nlp, overwrite_ents=True)

推荐阅读