在 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
中进行了一些自省(introspection),我也找不到原始规则名称。如果有人可以帮助我,那就太好了。
非常感谢你。
最佳答案
是的——您可以简单地在 StringStore
中查找 ID。您的词汇量,可通过 nlp.vocab.strings
或 doc.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'
.
关于nlp - 在 spacy 中,是否可以在匹配的匹配中获取相应的规则 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47493897/