在 EntityRuler 中使用 RegEx 作为短语模式

Nem*_*emo 6 python spacy

我尝试FRT使用 EntityRuler查找实体,如下所示:

from spacy.lang.en import English
from spacy.pipeline import EntityRuler

nlp = English()
ruler = EntityRuler(nlp)
patterns = [{"label": "FRT", "pattern": [{'REGEX': "[Aa]ppl[e|es])"}]},
            {"label": "BRN", "pattern": [{"LOWER": "granny"}, {"LOWER": "smith"}]}]

ruler.add_patterns(patterns)
nlp.add_pipe(ruler)

doc = nlp(u"Apple is red. Granny Smith apples are green.")
print([(ent.text, ent.label_) for ent in doc.ents])
Run Code Online (Sandbox Code Playgroud)

然后我得到了这个结果

[('Apple', 'FRT'), ('is', 'FRT'), ('red', 'FRT'), ('.', 'FRT'), ('Granny Smith', 'BRN'), ('apples', 'FRT'), ('is', 'FRT'), ('green', 'FRT'), ('.', 'FRT')]
Run Code Online (Sandbox Code Playgroud)

你能告诉我如何修复我的代码,以便我得到这个结果

[('Apple', 'FRT'), ('Granny Smith', 'BRN'), ('apples', 'FRT')]
Run Code Online (Sandbox Code Playgroud)

先感谢您。

Wik*_*żew 6

您需要使用以下patterns声明修复整个代码:

patterns = [{"label": "FRT", "pattern": [{"TEXT" : {"REGEX": "[Aa]pples?"}}]},
            {"label": "BRN", "pattern": [{"LOWER": "granny"}, {"LOWER": "smith"}]}]
Run Code Online (Sandbox Code Playgroud)

有两件事情:1)REGEX运营商本身不工作,如果你没有下定义它TEXTLOWER顶级令牌和2)您使用的正则表达式是腐败,你正在使用一个字符类,而不是一个分组构造。

需要注意的是[e|es],作为一个正则表达式字符类,匹配es|。因此,如果您有一个Appl| is red.字符串,则结果将包含[('Appl|', 'FRT'). 您需要使用非捕获组- (?:es|s),或者只es?匹配一个e然后是一个可选的s.

另外,参见 这些场景:

  • [{"TEXT" : {"REGEX": "[Aa]pples?"}}]会找到Apple, apple, Apples, apples,但不会找到APPLES
  • [{"LOWER" : {"REGEX": "apples?"}}]会找到Apple, apple, Apples, apples, APPLES,aPPleS还有stapples(拼写错误staples
  • [{"TEXT" : {"REGEX": r"\b[Aa]pples?\b"}}]会找到Apple, apple, Apples, apples,但不会找到APPLES也不会 stapples因为\b字边界。

  • @Nemo 我通常的建议是:我可以建议初学者在 [regexone.com](http://regexone.com/) 上完成所有课程,通读 [regular-expressions.info](http://www.regular- Expressions.info)、[正则表达式 SO 标签描述](http://stackoverflow.com/tags/regex/info)(以及许多其他优秀在线资源的链接),以及名为 [正则表达式含义是什么] 的社区 SO 帖子(http://stackoverflow.com/questions/22937618/reference-what-does-this-regex-mean)。[rexegg.com](http://rexegg.com) 值得一看。您还应该检查[Python `re` 文档](https://docs.python.org/3/library/re.html)。 (2认同)