【问题标题】:Using custom Token extensions in spaCy's Matcher在 spaCy 的 Matcher 中使用自定义令牌扩展
【发布时间】:2020-07-26 10:13:35
【问题描述】:

我刚刚在 spaCy 中为 Token 添加了以下扩展:

from spacy.tokens import Token
has_dep = lambda token,name: name in [child.dep_ for child in token.children]
Token.set_extension('HAS_DEP', method=has_dep)

所以,我想检查一个令牌是否有某个指定的依赖名称作为它的孩子之一,所以如下:

doc = nlp(u'We are walking around.')
walking = doc[2]
walking._.HAS_DEP('nsubj')

输出True,因为'walking'有一个依赖标签为'nsubj'的孩子(即单词'we' )。

但是,我不明白如何将此扩展程序与 spaCy 的 Matcher 一起使用。下面是我写的。我期望的输出是walking,但它似乎不起作用:

matcher = Matcher(nlp.vocab)

pattern = [
    {"_": {"HAS_DEP": {'name': 'nsubj'}}}  # this is the line I'm not sure of
    ]

matcher.add("depnsubj", None, pattern)

doc = nlp("We're walking around the house.")
matches = matcher(doc)

for match_id, start, end in matches:
    string_id = nlp.vocab.strings[match_id]  
    span = doc[start:end]
    print(span)

【问题讨论】:

    标签: python methods nlp spacy matcher


    【解决方案1】:

    我认为您的目标可能会通过getter 实现:

    import spacy
    from spacy.matcher import Matcher
    from spacy.tokens import Token
    has_dep = lambda token: 'nsubj' in [child.dep_ for child in token.children]
    Token.set_extension('HAS_DEP_NSUBJ', getter=has_dep, force=True)
    
    nlp = spacy.load("en_core_web_md")
    matcher = Matcher(nlp.vocab)
    matcher.add("depnsubj", None, [{"_": {"HAS_DEP_NSUBJ": True}}])
    
    doc = nlp("We're walking around the house.")
    matches = matcher(doc)
    
    for match_id, start, end in matches:
        string_id = nlp.vocab.strings[match_id]  
        span = doc[start:end]
        print(span)
    
    walking
    

    【讨论】:

    • 由于Matcher 模式没有为扩展提供依赖标签名称的机制,我认为这是最接近的工作解决方案。
    【解决方案2】:

    我认为您可以改用doc.retokenize()token.head,如下所示:

    from spacy.matcher import Matcher
    import en_core_web_sm
    
    nlp = en_core_web_sm.load()
    
    matcher = Matcher(nlp.vocab)
    pattern = [{'DEP': 'nsubj'}]
    matcher.add("depnsubj", None, pattern)
    
    doc = nlp("We're walking around the house.")
    matches = matcher(doc)
    
    matched_spans = []
    for match_id, start, end in matches:
        span = doc[start:end]
        matched_spans.append(doc[start:end])
    
    matched_tokens = []
    with doc.retokenize() as retokenizer:
        for span in spans:
            retokenizer.merge(span)
            for token in span:
                print(token.head)
    

    输出:

    walking
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多