如何对句子列表进行词形还原

6 python list nltk lemmatization

如何在 Python 中对句子列表进行词形还原?

from nltk.stem.wordnet import WordNetLemmatizer
a = ['i like cars', 'cats are the best']
lmtzr = WordNetLemmatizer()
lemmatized = [lmtzr.lemmatize(word) for word in a]
print(lemmatized)
Run Code Online (Sandbox Code Playgroud)

这是我尝试过的,但它给了我相同的句子。我需要在正常工作之前对单词进行标记吗?

alv*_*vas 7

长话短说

pip3 install -U pywsd
Run Code Online (Sandbox Code Playgroud)

然后:

>>> from pywsd.utils import lemmatize_sentence

>>> text = 'i like cars'
>>> lemmatize_sentence(text)
['i', 'like', 'car']
>>> lemmatize_sentence(text, keepWordPOS=True)
(['i', 'like', 'cars'], ['i', 'like', 'car'], ['n', 'v', 'n'])

>>> text = 'The cat likes cars'
>>> lemmatize_sentence(text, keepWordPOS=True)
(['The', 'cat', 'likes', 'cars'], ['the', 'cat', 'like', 'car'], [None, 'n', 'v', 'n'])

>>> text = 'The lazy brown fox jumps, and the cat likes cars.'
>>> lemmatize_sentence(text)
['the', 'lazy', 'brown', 'fox', 'jump', ',', 'and', 'the', 'cat', 'like', 'car', '.']
Run Code Online (Sandbox Code Playgroud)

否则,看看该函数如何pywsd

  • 对字符串进行标记
  • 使用 POS 标记器并映射到 WordNet POS 标记集
  • 尝试阻止
  • 最后用 POS 和/或词干调用词形还原器

请参阅https://github.com/alvations/pywsd/blob/master/pywsd/utils.py#L129


DYZ*_*DYZ 5

您必须单独对每个单词进行词形还原。相反,您对句子进行词形还原。正确的代码片段:

from nltk.stem.wordnet import WordNetLemmatizer
from nltk import word_tokenize
sents = ['i like cars', 'cats are the best']
lmtzr = WordNetLemmatizer()
lemmatized = [[lmtzr.lemmatize(word) for word in word_tokenize(s)]
              for s in sents]
print(lemmatized)
#[['i', 'like', 'car'], ['cat', 'are', 'the', 'best']]
Run Code Online (Sandbox Code Playgroud)

如果您首先进行词性标注,然后将词性信息提供给词形还原器,您也可以获得更好的结果。