首页 > 解决方案 > 如何让 SpaCy 选择由“and”或“,”分隔的名词块作为一个

问题描述

我很抱歉标题,我真的不知道如何表达它,但希望这个例子能说明清楚。

基本上,

对于下面的句子:

阿什利和布赖恩在喝水。

我希望名词块是“Ashley and Brian”而不是“Ashley”、“Brian”

另一个例子是:

衣服的种类包括衬衫、裤子和裤子。

我希望名词块是“衬衫、裤子和裤子”而不是“衬衫”“裤子”“裤子”

我该如何解决这个问题?

标签: spacyspacy-3

解决方案


您所描述的不是名词块。该conjuncts功能更接近您想要的。

这可能不适用于复杂的句子,但至少它会涵盖您的示例和典型案例。

import spacy

nlp = spacy.load("en_core_web_sm")

texts = [
        "Ashley and Brian are drinking water.",
        "Types of clothes include shirts, pants and trousers.",
        ]

for text in texts:
    print("-----")
    print(text)
    checked = 0
    doc = nlp(text)
    for tok in doc:
        if tok.i < checked: continue
        if tok.pos_ not in ('NOUN', 'PROPN'): continue

        if tok.conjuncts:
            print(doc[tok.left_edge.i:tok.right_edge.i+1])
            checked = tok.right_edge.i + 1

推荐阅读