【问题标题】:Spacy Matcher Pattern空间匹配器模式
【发布时间】:2021-09-28 13:39:13
【问题描述】:
import spacy
from spacy.matcher import DependencyMatcher

nlp = spacy.load("en_core_web_sm")

pattern = [
  {
    "RIGHT_ID": "target",
    "RIGHT_ATTRS": {"POS": "NOUN"}
  },

  {
    "LEFT_ID": "target",
    "REL_OP": ">",
    "RIGHT_ID": "verb",
    "RIGHT_ATTRS": {"POS": {"IN": ["VERB"]}}
  },
    {
    "LEFT_ID": "target",
    "REL_OP": ">",
    "RIGHT_ID": "adj",
    "RIGHT_ATTRS": {"POS": {"IN": ["ADJ"]}}
  }
]

matcher = DependencyMatcher(nlp.vocab)
matcher.add("FOUNDED", [pattern])

text = "the bag that I bought is really beautiful"
doc = nlp(text)
for match_id, (target, verb, adj) in matcher(doc):
    print(doc[target], doc[verb], doc[adj])

嗨,我正在学习如何使用 Spacy Matcher,我正在做一些测试以找到与名词相关的动词和形容词。 希望得到“包买得漂亮”的结果。 我什么也没得到,我不知道我做错了什么。任何的想法 ?谢谢!

【问题讨论】:

    标签: python spacy matcher


    【解决方案1】:

    如果依赖匹配器没有按照您认为的方式工作,请查看依赖解析!

    import spacy
    
    nlp = spacy.load("en_core_web_sm")
    
    text = "the bag that I bought is really beautiful"
    doc = nlp(text)
    
    for tok in doc:
        print(tok.i, tok, tok.pos_, tok.dep_, tok.head.i, sep="\t")
    

    输出:

    0       the     DET     det     1
    1       bag     NOUN    nsubj   5
    2       that    DET     dobj    4
    3       I       PRON    nsubj   4
    4       bought  VERB    relcl   1
    5       is      AUX     ROOT    5
    6       really  ADV     advmod  7
    7       beautiful       ADJ     acomp   5
    

    在这里你可以看到“beautiful”不是以“bought”为中心,而是以“is”为中心,因为“is”是句子中的主要动词。由于您使用“>”作为 rel op,因此您不会得到匹配,因为“beautiful”不在“bought”的直接下方——事实上,它根本不在它的下方。所以如果你想匹配这句话,你需要重新考虑你的规则。坦率地说,如果你想匹配这样的关系从句,这会有点困难,因为 ADJ 基本上可以在树中的任何位置。

    请注意,您的规则几乎与“我买了一个漂亮的包”之类的简单句子匹配,但这也不起作用,因为“包”动词之下,而不是在它之上。使用动词作为锚点通常更容易,因为它们在树中的位置较高。

    【讨论】:

      猜你喜欢
      • 2013-10-09
      • 1970-01-01
      • 2023-03-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多