如何使用nlp库使复合词成为单数?

2w2cym1i  于 2021-07-13  发布在  Java
关注(0)|答案(1)|浏览(332)

发行

我试着用空格把复合词从复数变成单数。
但是,我无法修复将复数转换为单数作为复合词的错误。
如何获得下面的首选输出?

cute dog
two or three word
the christmas day

开发环境
python 3.9.1版

错误

print(str(nlp(word).lemma_))
AttributeError: 'spacy.tokens.doc.Doc' object has no attribute 'lemma_'

代码

import spacy
nlp = spacy.load("en_core_web_sm")

words = ["cute dogs", "two or three words", "the christmas days"]

for word in words:
    print(str(nlp(word).lemma_))

审判

cute
dog
two
or
three
word
the
christmas
day
import spacy
nlp = spacy.load("en_core_web_sm")

words = ["cute dogs", "two or three words", "the christmas days"]

for word in words:
    word = nlp(word)
    for token in word:
        print(str(token.lemma_))
z6psavjg

z6psavjg1#

正如你所发现的,你不能得到一个博士的引理,只能得到单个单词的引理。在英语中,多词表达没有引理,引理只适用于单个词。然而,在英语中,复合词的复数化只是通过将最后一个单词的复数化,所以你可以将最后一个单词单数化。举个例子:

import spacy

nlp = spacy.load("en_core_web_sm")

def make_compound_singular(text):
    doc = nlp(text)

    if len(doc) == 1:
        return doc[0].lemma_
    else:
        return doc[:-1].text + doc[-2].whitespace_ + doc[-1].lemma_

texts = ["cute dogs", "two or three words", "the christmas days"]
for text in texts:
    print(make_compound_singular(text))

相关问题