【问题标题】:Spacy matcher pattern with specifics nouns带有特定名词的 Spacy 匹配器模式
【发布时间】:2021-12-30 17:22:58
【问题描述】:

我正在尝试匹配一个特定的模式:任何以 s、t 或 l 结尾的名词的动词。 例如。: 像猫一样, 吃饭, 制作香料

我该怎么做?

我知道我在这样做:

nlp =spacy.load("en_core_web_sm")
matcher = Matcher(nlp.vocable)
pattern = [{"POS": "VERB"}, {"POS": "NOUN"}]
matcher.add("mypattern", [pattern])
​doc = nlp(Verbwithnoun)
matches = matcher(doc)

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

但这会打印所有带有名词的动词,而不是以 t,l 或 s 结尾的名词。如何让 spacy 只匹配以 t、l 或 s 结尾的特定名词?

【问题讨论】:

    标签: python python-3.x spacy spacy-3


    【解决方案1】:

    您可以通过检查您得到的短语是否以三个字母中的任何一个结尾来对结果进行后处理:

    import spacy
    from spacy.matcher import Matcher
    
    nlp = spacy.load("en_core_web_sm")
    matcher = Matcher(nlp.vocab)
    pattern = [{"POS": "VERB"}, {"POS": "DET", "OP" : "?"}, {"POS": "NOUN"}]
    matcher.add("mypattern", [pattern])
    Verbwithnoun = "I know the language. I like the cat, I eat a meal, I make spices."
    doc = nlp(Verbwithnoun)
    matches = matcher(doc)
    
    for match_id, start, end in matches:
        string_id = nlp.vocab.strings[match_id] 
        phrase = doc[start:end]
        if phrase.text.endswith('s') or phrase.text.endswith('t') or phrase.text.endswith('l'):
            print(doc[start:end])
    

    输出:

    like the cat
    eat a meal
    make spices
    

    【讨论】:

      【解决方案2】:

      后处理很好,但您也可以直接在模式中使用正则表达式。见the docs

      nlp =spacy.load("en_core_web_sm")
      matcher = Matcher(nlp.vocable)
      pattern = [{"POS": "VERB"}, {"POS": "NOUN", "TEXT": {"REGEX": "[lst]$"}}]
      matcher.add("mypattern", [pattern])
      ​doc = nlp(Verbwithnoun)
      matches = matcher(doc)
      
      for match_id, start, end in matches:
      string_id = nlp.vocab.strings[match_id] 
      print(doc[start:end)
      

      【讨论】:

      • 非常感谢 polm23,这就是我要找的东西!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-12
      • 1970-01-01
      • 1970-01-01
      • 2018-12-10
      • 2017-04-28
      相关资源
      最近更新 更多