【问题标题】:Spacy: How to get all words that describe a noun?Spacy:如何获得描述名词的所有单词?
【发布时间】:2021-08-21 13:23:27
【问题描述】:

我是 spacy 和整体 nlp 的新手。

为了理解 spacy 的工作原理,我想创建一个函数,它接受一个句子并返回一个字典、元组或列表,其中包含名词和描述它的单词。

我知道 spacy 创建了一个句子树并且知道每个单词的用法(显示在 displacy 中)。

但是正确的获取方式是:

“有两个黄色洗碗机的大房间”

收件人:

{名词:“房间”,形容词:“大”} {名词:“洗碗机”,adj:“黄色”,adv:“两个”}

或任何其他解决方案,可以在可用包中提供所有相关单词。

提前致谢!

【问题讨论】:

    标签: python nlp spacy


    【解决方案1】:

    你想做的叫做“名词块”:

    import spacy
    nlp = spacy.load('en_core_web_md')
    txt = "A large room with two yellow dishwashers in it"
    doc = nlp(txt)
    
    chunks = []
    for chunk in doc.noun_chunks:
        out = {}
        root = chunk.root
        out[root.pos_] = root
        for tok in chunk:
            if tok != root:
                out[tok.pos_] = tok
        chunks.append(out)
    print(chunks)
    

    [
     {'NOUN': room, 'DET': A, 'ADJ': large}, 
     {'NOUN': dishwashers, 'NUM': two, 'ADJ': yellow}, 
     {'PRON': it}
    ]
    

    您可能会注意到“名词块”并不能保证词根始终是名词。如果您希望仅将结果限制为名词:

    chunks = []
    for chunk in doc.noun_chunks:
        out = {}
        noun = chunk.root
        if noun.pos_ != 'NOUN':
            continue
        out['noun'] = noun
        for tok in chunk:
            if tok != noun:
                out[tok.pos_] = tok
        chunks.append(out)
        
    print(chunks)
    

    [
     {'noun': room, 'DET': A, 'ADJ': large}, 
     {'noun': dishwashers, 'NUM': two, 'ADJ': yellow}
    ]
    

    【讨论】:

      【解决方案2】:

      这是DependencyMatcher 的一个非常简单的用法。

      import spacy
      from spacy.matcher import DependencyMatcher
      
      nlp = spacy.load("en_core_web_sm")
      
      pattern = [
        {
          "RIGHT_ID": "target",
          "RIGHT_ATTRS": {"POS": "NOUN"}
        },
        # founded -> subject
        {
          "LEFT_ID": "target",
          "REL_OP": ">",
          "RIGHT_ID": "modifier",
          "RIGHT_ATTRS": {"DEP": {"IN": ["amod", "nummod"]}}
        },
      ]
      
      matcher = DependencyMatcher(nlp.vocab)
      matcher.add("FOUNDED", [pattern])
      
      text = "A large room with two yellow dishwashers in it"
      doc = nlp(text)
      for match_id, (target, modifier) in matcher(doc):
          print(doc[modifier], doc[target], sep="\t")
      

      输出:

      large   room
      two dishwashers
      yellow  dishwashers
      

      应该很容易把它变成字典或任何你喜欢的东西。您可能还想修改它以将专有名词作为目标,或支持其他类型的依赖关系,但这应该是一个好的开始。

      您可能还想查看noun chunks 功能。

      【讨论】:

      • 抱歉回复晚了,但谢谢你这正是我正在寻找的输出!即使我不完全理解您的代码中发生了什么:) 但我认为阅读您发送的文档会有所帮助:)
      • 我希望您在我对此发表评论时收到通知 :) 我能够理解 Attrs 和模式本身,但我似乎没有找到任何关于 id 的信息:那里有哪些可能的 id目标和修饰符是什么意思?另外,在这种情况下,我真的不明白相关运营商使用的是什么.. 如果您有时间给我一个简短的解释或文档链接,我会很高兴 :)谢谢!
      • ID 是你编的名字,可以是任何东西。操作员来自 Semgrex。该文档已链接在我的答案顶部,并解释了这两件事。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-04-24
      • 1970-01-01
      • 2020-04-18
      • 1970-01-01
      • 2018-10-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多