首页 > 解决方案 > SpaCy 基于规则的人员模式匹配

问题描述

我尝试使用 Spacy 模式来匹配我的文本中与人的不同表面形状相对应的:LASTNAME, FIRSTNAME或/FIRSTNAME, LASTNAME和/或FIRSTNAME LASTNAME(无点)。

我试试这个:

import spacy

# create a nlp object with pretrained model
nlp = spacy.load('fr_core_news_lg')
ruler = nlp.add_pipe("entity_ruler", after='ner') 

# define the patterns
patterns = [{"label":"PER", "pattern":[{"LOWER":"jules"},{"LOWER":"michelet"}]},
            {"label":"PER", "pattern": [{"LOWER":"jean joseph"},{"LOWER":"laborde"}]},
            ]

specific_forms_patterns_persons = [
    {"label": "PER", "pattern": [{"ENT_TYPE": "PER"}, {"IS_PUNCT": True}, {"ENT_TYPE": "PER"}]}
    ]

# add patterns to ruler
ruler.add_patterns(patterns)
ruler.add_patterns(specific_forms_patterns_persons)

# convert the input sentence into the document object using the 'nlp'
doc = nlp("Jules, Michelet avec Laborde, Jean Joseph et Jacques Mei à Paris.")

# print the entities in the sentenced after adding the EntityRuler matcher
print([(ent.text, ent.label_) for ent in doc.ents])

我得到这个输出:

[('Jules', 'PER'), ('Michelet', 'PER'), ('Laborde', 'PER'), ('Jean Joseph', 'PER'), ('Jacques Mei', 'PER'), ('Paris', 'LOC')]

虽然我想得到:

[('Jules, Michelet', 'PER'), ('Laborde, Jean Joseph', 'PER'), ('Jacques Mei', 'PER'), ('Paris', 'LOC')]

我尝试使用以下方式自定义我的模式:

specific_forms_patterns_persons = [
    {"label": "PER", "pattern": [{"ENT_TYPE": "PER"}, {"ORTH": ","}, {"ENT_TYPE": "PER"}]}
    ]

但我仍然得到相同的输出。最好训练一个 spacy 模型来识别这些特定的形状,但我想知道这是否只能通过规则来实现。

标签: pythonpython-3.xnlpspacynamed-entity-recognition

解决方案


您需要在 中使用overwrite_entsEntityRuler否则它不会更改现有标签。

cfg = {"overwrite_ents": True}
ruler = nlp.add_pipe("entity_ruler", after='ner', config=cfg)

您还应该考虑使用 匹配多个PER令牌OP来处理“Laborde, Jean Joseph”案例。

请注意,在处理您的模式时,我建议您避免使用现有的标签,例如PER,因为它很难理解什么是预先存在的注释以及什么是您的。直到你最终确定它的用途MYPER或其他东西。


推荐阅读