Python Spacy实体标尺正则表达式模式无法识别匹配
我正在使用spacy实体标尺为我的域构建一个自定义的ner 我有一些文本,我想从文本中提取实体,但是单词可能在开头包含Python Spacy实体标尺正则表达式模式无法识别匹配,python,regex,spacy,Python,Regex,Spacy,我正在使用spacy实体标尺为我的域构建一个自定义的ner 我有一些文本,我想从文本中提取实体,但是单词可能在开头包含#或@。我并没有为每种模式创建新的模式,而是尝试使用正则表达式模式匹配器 代码: from spacy.lang.en import English from spacy.pipeline import EntityRuler team_words = [{ 'id': '111', 'name': "fnatic" },{ 'id': '2
#
或@
。我并没有为每种模式创建新的模式,而是尝试使用正则表达式模式匹配器
代码:
from spacy.lang.en import English
from spacy.pipeline import EntityRuler
team_words = [{
'id': '111',
'name': "fnatic"
},{
'id': '222',
'name': "100 thieves"
}]
team_patterns = [{
'label': 'TEAM',
'pattern': [{'TEXT': {'REGEX': f"^(#|@?){w['name']}"}}],
'id': w['id']
} for w in team_words]
# { 'label': 'TEAM', 'pattern': "100 thieves", 'id': '222' }
nlp = English()
ruler = EntityRuler(nlp)
patterns = team_patterns
ruler.add_patterns(patterns)
nlp.add_pipe(ruler)
# expect it to match 100 thieves but it does not
doc = nlp("text text text 100 thieves text text text")
print([(ent.text, ent.label_, ent.ent_id_) for ent in doc.ents])
## working however the # in #fnatic is not present in the ent.text output
doc = nlp("text text text #fnatic @fnatic fnatic text text text")
print([(ent.text, ent.label_, ent.ent_id_) for ent in doc.ents])
## expect it not to match but it does
doc = nlp("text text text fnatichello text text text")
print([(ent.text, ent.label_, ent.ent_id_) for ent in doc.ents])
输出
[]
[('fnatic', 'TEAM', '111'), ('@fnatic', 'TEAM', '111'), ('fnatic', 'TEAM', '111')]
[('fnatichello', 'TEAM', '111')]
我对上述代码的结果有3个问题
#fnatic
的ent.text似乎缺少标签
fnatic
单词应该在那里结束。所以这个不应该匹配
对于3),您只需要在正则表达式的末尾使用
$
,{'regex':fr“^[#@]?{w['name']}$“}}
。至于1),REGEX
只在一个令牌内匹配,100小偷
是两个令牌。@WiktorStribiżew嘿,谢谢你的回复,你确定1)因为如果我使用“{'label':'TEAM','pattern':'100小偷','id':'222'}它匹配是的,如果你使用TEAMżpatterns.append,你就不用REGEX了({'label':'TEAM','pattern':[{'TEXT':{'REGEX':“100小偷”}],'id':'222})
它不再返回100小偷
了。#fnatic
也有同样的问题:它被标记为两个标记,'#','fnatic'
好吧,但我不明白为什么将正则表达式模式设置为与非正则表达式模式相匹配会导致其标记不同?你是如何确定的?