将REGEX实体添加到Spacy&39;的匹配器 [英] Adding REGEX entities to SpaCy's Matcher

查看:43
本文介绍了将REGEX实体添加到Spacy&39;的匹配器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将正则表达式定义的实体添加到Spacy的NER管道。理想情况下,我应该能够使用从具有已定义实体类型的json文件加载的任何正则表达式。例如,我正在尝试执行下面的代码。

下面的代码显示了我正在尝试做的事情,遵循Spacy关于使用正则表达式的自定义属性的讨论中给出的示例。我尝试过以各种方式(Doc、Span、Token)调用‘Set_Extension’方法,但都无济于事。我甚至不确定我应该将它们设置为什么。

    nlp = spacy.load("en_core_web_lg")
    matcher = Matcher(nlp.vocab)
    pattern = [{"_": {"country": {"REGEX": "^[Uu](.?|nited) ?[Ss](.|tates)$"}}}]
    matcher.add("US", None, pattern)
    doc = nlp(u"I'm from the United States.")
    matches = matcher(doc)
    for match_id, start, end in matches:
        string_id = nlp.vocab.strings[match_id]
       span = doc[start:end]
       print(match_id, string_id, start, end, span.text)

我希望match_id, string_id 3 4 United States打印出来。

相反,我得到的是AttributeError: [E046] Can't retrieve unregistered extension attribute 'country'. Did you forget to call the 'set_extension' method?

推荐答案

这里有关于扩展属性的文档:https://spacy.io/usage/processing-pipelines#custom-components-attributes

基本上,您必须将这个country变量定义为扩展属性,如下所示:

Token.set_extension("country", default="")
然而,在您引用的代码中,您从未将_.country属性实际设置为任何标记(或范围),因此它们都仍然是缺省值,匹配器永远无法匹配它们。您引用的这句话:

pattern = [{"_": {"country": {"REGEX": "^[Uu](.?|nited) ?[Ss](.?|tates)$"}}}]

尝试在自定义属性值上匹配美国正则表达式,而不是像您预期的那样(我认为)在文档文本上匹配。

一种解决方案是直接对文本运行reg-exp:

nlp = spacy.load("en_core_web_lg")
matcher = Matcher(nlp.vocab)
pattern = [{"TEXT": {"REGEX": "^[Uu](.?|nited)$"}},
           {"TEXT": {"REGEX": "^[Ss](.?|tates)$"}}]
matcher.add("US", None, pattern)
doc = nlp(u"I'm from the United States.")
matches = matcher(doc)
for match_id, start, end in matches:
    string_id = nlp.vocab.strings[match_id]
    span = doc[start:end]
    print(match_id, string_id, start, end, span.text)

哪些输出

15397641858402276818美国4 6美国

然后,您可以使用这些匹配来设置范围或令牌的自定义属性(在本例中为Span,因为您的匹配可能涉及多个令牌)

这篇关于将REGEX实体添加到Spacy&39;的匹配器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆