How to lemmatize a list of sentences

时间:2018-06-04 16:51:22

标签: python list nltk lemmatization

How can I lemmatize a list of sentences in 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)

This is what I've tried but it gives me the same sentences. Do I need to tokenize the words before to work properly?

2 个答案:

答案 0 :(得分:2)

<强> TL; DR

pip3 install -U pywsd

然后:

>>> 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', '.']

否则,请查看pywsd中的函数:

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

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

答案 1 :(得分:1)

你必须分别对每个单词进行词形变换。相反,你将句子列为lematize。正确的代码片段:

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']]

如果您首先进行POS标记,然后将POS信息提供给词形变换器,您也可以获得更好的结果。