簡體   English   中英

名詞短語合並后,如何獲得句子的正確 pos 標簽?

[英]How do I get the correct pos tags for a sentence after noun phrase merging?

我正在嘗試合並一個句子中的名詞短語塊,然后獲取合並文檔中每個標記的 pos 標簽。 但是,對於每個合並的跨度,我似乎獲得了跨度中第一個標記的 pos 標記(通常是 DET 或 ADJ)而不是 NOUN。

這是代碼:

def noun_chunk_retokenizer(doc):
    with doc.retokenize() as retokenizer:
        for chunk in doc.noun_chunks:
            retokenizer.merge(chunk)
    return doc

nlp = spacy.load('en_core_web_sm')
nlp.add_pipe(noun_chunk_retokenizer)

query = "when is the tennis match happening?"
[(c.text,c.pos_) for c in nlp(query)]

這是我得到的結果:

[('when', 'ADV'),
 ('is', 'VERB'),
 ('the tennis match', 'DET'),
 ('happening', 'VERB'),
 ('?', 'PUNCT')]

但我希望“網球比賽”被標記為“名詞”,這就是它在顯示演示中的工作方式: https ://explosion.ai/demos/displacy?

似乎應該有一種“標准”的方式來做到這一點,但我不確定如何。

您應該使用內置的merge_noun_chunks組件 請參閱 管道函數文檔

將名詞塊合並為一個標記。 也可以通過字符串名稱"merge_noun_chunks" 初始化后,通常使用nlp.add_pipe將組件添加到處理管道中。

字符串的示例用法:

import spacy
nlp = spacy.load('en_core_web_sm')
nlp.add_pipe(nlp.create_pipe('merge_noun_chunks'))
query = "when is the tennis match happening?"
[(c.text,c.pos_) for c in nlp(query)]

輸出:

[('when', 'ADV'),
 ('is', 'VERB'),
 ('the tennis match', 'NOUN'),
 ('happening', 'VERB'),
 ('?', 'PUNCT')]

至於“如何在源代碼中完成”的問題,請參閱第 7 行的spacy Github repo , /spaCy/blob/master/spacy/pipeline/functions.py文件:

def merge_noun_chunks(doc):
    """Merge noun chunks into a single token.
    doc (Doc): The Doc object.
    RETURNS (Doc): The Doc object with merged noun chunks.
    DOCS: https://spacy.io/api/pipeline-functions#merge_noun_chunks
    """
    if not doc.is_parsed:
        return doc
    with doc.retokenize() as retokenizer:
        for np in doc.noun_chunks:
            attrs = {"tag": np.root.tag, "dep": np.root.dep}
            retokenizer.merge(np, attrs=attrs)
    return doc

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM