Python Spacy实体标尺正则表达式模式无法识别匹配

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

我正在使用spacy实体标尺为我的域构建一个自定义的ner

我有一些文本,我想从文本中提取实体,但是单词可能在开头包含
#
@
。我并没有为每种模式创建新的模式,而是尝试使用正则表达式模式匹配器

代码

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个问题

  • 100小偷在使用模式文本regex时根本不匹配。我试图添加一个反斜杠以逃避“”的约束,但这不起作用。好像是空间有问题?然而,如果你做一个简单的模式匹配,它将工作

  • 这一条基本正确,它将所有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'
    好吧,但我不明白为什么将正则表达式模式设置为与非正则表达式模式相匹配会导致其标记不同?你是如何确定的?