繁体   English   中英

Spacy 匹配器返回规则模式

[英]Spacy matcher return Rule patterns

我需要 spacy 中基于规则的匹配器的帮助。 我有这个代码:

import spacy
from spacy.matcher import Matcher

nlp = spacy.load("en_core_web_sm")
matcher = Matcher(nlp.vocab)
# Add match ID "HelloWorld" with no callback and one pattern
pattern = [{"LOWER": "hello"}, {"IS_PUNCT": True}, {"LOWER": "world"}]
pattern = [{"LOWER": "Good"}, {"IS_PUNCT": True}, {"LOWER": "night"}]

matcher.add("HelloWorld", [pattern])

doc = nlp("Hello, world! Hello world!")
matches = matcher(doc)
for match_id, start, end in matches:
    string_id = nlp.vocab.strings[match_id]  # Get string representation
    span = doc[start:end]  # The matched span
    print(match_id, string_id, start, end, span.text)

一切正常我得到了match_id,string_id等......但我问自己是否有可能获得与匹配范围相对应的模式:

本质上,我想知道是否有可能在 spacy 中获得与匹配对应的模式:

例如在我的例子中,

[{"LOWER": "hello"}, {"IS_PUNCT": True}, {"LOWER": "world"}]

是我的示例的相应匹配项。

非常感谢

如果使用相同的 label 添加多个模式,则事后您无法找到匹配的模式。

您可以做几件事。 一个非常简单的方法是为每种模式使用不同的标签。 另一种选择是将 模式 ID与 EntityRuler 一起使用。

对于所有唯一命名的模式,您可以使用涉及使用字典列表的解决方法,其中键是模式名称,值是实际模式。 获得匹配后,您可以通过模式名称获取模式:

import spacy
from spacy.matcher import Matcher
nlp = spacy.load("en_core_web_sm")
matcher = Matcher(nlp.vocab)
patterns = [                                                         # Define patterns
    {'HelloWorld': [{"LOWER": "hello"}, {"IS_PUNCT": True}, {"LOWER": "world"}]},
    {'GoodNight': [{"LOWER": "good"}, {"LOWER": "night"}]}
]
for p in patterns:                                        # Adding patterns to matcher
    for name,pattern in p.items():
        matcher.add(name, [pattern])
doc = nlp("Hello, world! Hello world! Good night!")
matches = matcher(doc)
for match_id, start, end in matches:
    string_id = nlp.vocab.strings[match_id]  # Get string representation
    span = doc[start:end]  # The matched span
    print(match_id, string_id, start, end, span.text)
    print("The pattern is:", [p for p in patterns if string_id in p][0][string_id])

Output:

15578876784678163569 HelloWorld 0 3 Hello, world
The pattern is: [{'LOWER': 'hello'}, {'IS_PUNCT': True}, {'LOWER': 'world'}]
15528765659627300253 GoodNight 7 9 Good night
The pattern is: [{'LOWER': 'good'}, {'LOWER': 'night'}]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM