【问题标题】:In spacy, Is it possible to get the corresponding rule id in a match of matches在 spacy 中,是否可以在匹配的匹配中获取相应的规则 ID
【发布时间】:2017-11-26 07:21:37
【问题描述】:

在 Spacy 2.x 中,我使用匹配器在我的文本语料库中查找特定标记。每个规则都有一个 ID(例如'class-1_0')。在解析期间,我使用回调 on_match 来处理每个匹配项。有没有办法直接在回调中检索用于查找匹配的规则。

这是我的示例代码。

txt = ("Aujourd'hui, je vais me faire une tartine au beurre "
       "de cacahuète, c'est un pilier de ma nourriture "
       "quotidienne.")

nlp = spacy.load('fr')

def on_match(matcher, doc, id, matches):
    span = doc[matches[id][1]:matches[id][2]]
    print(span)
    # find a way to get the corresponding rule without fuzz

matcher = Matcher(nlp.vocab)
matcher.add('class-1_0', on_match, [{'LEMMA': 'pilier'}])
matcher.add('class-1_1', on_match, [{'LEMMA': 'beurre'}, {'LEMMA': 'de'}, {'LEMMA': 'cacahuète'}])

doc = nlp(txt)
matches = matcher(doc)

在这种情况下matches 返回:

[(12071893341338447867, 9, 12), (4566231695725171773, 16, 17)]

12071893341338447867 是基于 class-1_0 的唯一 ID。即使我在matcher._patterns 中进行了一些自省,我也找不到原始规则名称。

如果有人可以帮助我,那就太好了。 非常感谢。

【问题讨论】:

    标签: nlp matcher spacy


    【解决方案1】:

    是的,您只需在StringStore 的词汇表中查找 ID,可通过 nlp.vocab.stringsdoc.vocab.strings 获得。通过Doc 在这里非常方便,因为您可以在on_match 回调中这样做:

    def on_match(matcher, doc, match_id, matches):
       string_id = doc.vocab.strings[match_id]
    

    为了提高效率,spaCy 将所有字符串编码为整数,并在StringStore 查找表中保留对映射的引用。在 spaCy v2.0 中,整数是散列值,因此它们将始终在模型和词汇表之间匹配。有关这方面的更多详细信息,请参阅this section in the docs

    当然,如果你的类和 ID 有点神秘,other answer 建议整数 ID 也可以正常工作。请记住,您选择的那些整数 ID 也可能会映射到 StringStore 中的某个随机字符串(如单词、词性标签或其他东西)。如果您不查找它们并将它们解析为某个地方的字符串,这通常无关紧要 - 但如果您这样做,输出可能会令人困惑。例如,如果您的匹配器规则 ID 是 99 并且您正在调用 doc.vocab.strings[99],这将返回 'VERB'

    【讨论】:

    • 谢谢。我测试了你的答案,它指向了正确的方向。但是要获取字符串 ID,您需要使用整数编码匹配规则,而不是 match_idstring_id = doc.vocab.strings[matches[id][0]] 再次感谢。
    • 感谢您在 spacy 2.0 上取得的令人难以置信的成就 :)
    【解决方案2】:

    在写我的问题时,我经常找到解决方案。

    这很简单,不用像class-1_0 那样使用unicode 规则ID,只需使用整数即可。标识符将在整个过程中保留。

    matcher.add(1, on_match, [{'LEMMA': 'pilier'}])
    

    匹配

    [(1, 16, 17),]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-20
      • 1970-01-01
      • 1970-01-01
      • 2022-08-14
      • 2010-10-24
      • 1970-01-01
      相关资源
      最近更新 更多