python-3.x - Spacy,具有跨越多个令牌的实体的匹配器
问题描述
我正在尝试创建一个匹配器,在文本中找到否定的自定义实体。它适用于跨越单个令牌的实体,但我在尝试捕获跨越多个令牌的实体时遇到了麻烦。
例如,假设我的自定义实体是动物(并标记为token.ent_type_ = "animal"
)
["cat", "dog", "artic fox"]
(注意最后一个实体有两个词)。
现在我想在文本中找到那些实体但被否定,所以我可以使用以下模式创建一个简单的匹配器:
[{'lower': 'no'}, {'ENT_TYPE': {'REGEX': 'animal', 'OP': '+'}}]
例如,我有以下文字:
There is no cat in the house and no artic fox in the basement
我可以成功捕获no cat
and no artic
,但最后一个匹配不正确,因为完整匹配应该是no artic fox
。这是由于OP: '+'
模式匹配单个自定义实体而不是两个。如何修改模式以将较长的匹配优先于较短的匹配?
解决方案
一种解决方案是使用doc retokenize 方法将每个多令牌实体的各个令牌合并为一个令牌:
import spacy
from spacy.pipeline import EntityRuler
nlp = spacy.load('en_core_web_sm', parse=True, tag=True, entity=True)
animal = ["cat", "dog", "artic fox"]
ruler = EntityRuler(nlp)
for a in animal:
ruler.add_patterns([{"label": "animal", "pattern": a}])
nlp.add_pipe(ruler)
doc = nlp("There is no cat in the house and no artic fox in the basement")
with doc.retokenize() as retokenizer:
for ent in doc.ents:
retokenizer.merge(doc[ent.start:ent.end])
from spacy.matcher import Matcher
matcher = Matcher(nlp.vocab)
pattern =[{'lower': 'no'},{'ENT_TYPE': {'REGEX': 'animal', 'OP': '+'}}]
matcher.add('negated animal', None, pattern)
matches = matcher(doc)
for match_id, start, end in matches:
span = doc[start:end]
print(span)
现在的输出是:
没有猫
没有北极狐
推荐阅读
- matlab - 在 MATLAB 中编写对数似然函数
- r - 添加日期到明年 1 月的行
- javascript - Vue组件里面使用jQuery
- python - python for android # 命令失败:/usr/bin/python -m pythonforandroid.toolchain
- python - pyautogui.locateCenterOnScreen 不断返回 NoneType 对象
- keras - 在 Watson 机器学习上部署使用自定义损失函数训练的模型
- python - 添加页面标题,img2pdf
- soap - 更改 zeep 绑定
- python - Cron Job 未在 centos 7 中执行
- agens-graph - 如何在 AgentGraph 上找到锁定等待查询?