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

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

发行

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

  1. cute dog
  2. two or three word
  3. the christmas day

开发环境
python 3.9.1版

错误

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

代码

  1. import spacy
  2. nlp = spacy.load("en_core_web_sm")
  3. words = ["cute dogs", "two or three words", "the christmas days"]
  4. for word in words:
  5. print(str(nlp(word).lemma_))

审判

  1. cute
  2. dog
  3. two
  4. or
  5. three
  6. word
  7. the
  8. christmas
  9. day
  1. import spacy
  2. nlp = spacy.load("en_core_web_sm")
  3. words = ["cute dogs", "two or three words", "the christmas days"]
  4. for word in words:
  5. word = nlp(word)
  6. for token in word:
  7. print(str(token.lemma_))
z6psavjg

z6psavjg1#

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

  1. import spacy
  2. nlp = spacy.load("en_core_web_sm")
  3. def make_compound_singular(text):
  4. doc = nlp(text)
  5. if len(doc) == 1:
  6. return doc[0].lemma_
  7. else:
  8. return doc[:-1].text + doc[-2].whitespace_ + doc[-1].lemma_
  9. texts = ["cute dogs", "two or three words", "the christmas days"]
  10. for text in texts:
  11. print(make_compound_singular(text))

相关问题