以下代码打印出leaf
:
from nltk.stem.wordnet import WordNetLemmatizer
lem = WordNetLemmatizer()
print(lem.lemmatize('leaves'))
取决于周围环境,这可能是也可能不准确,例如Mary leaves the room
与Dew drops fall from the leaves
。我怎样才能告诉NLTK将考虑周围环境的词语解释?
答案 0 :(得分:4)
首先标记句子,然后使用POS标签作为词形还原的附加参数输入。
from nltk import pos_tag
from nltk.stem import WordNetLemmatizer
wnl = WordNetLemmatizer()
def penn2morphy(penntag):
""" Converts Penn Treebank tags to WordNet. """
morphy_tag = {'NN':'n', 'JJ':'a',
'VB':'v', 'RB':'r'}
try:
return morphy_tag[penntag[:2]]
except:
return 'n'
def lemmatize_sent(text):
# Text input is string, returns lowercased strings.
return [wnl.lemmatize(word.lower(), pos=penn2morphy(tag))
for word, tag in pos_tag(word_tokenize(text))]
lemmatize_sent('He is walking to school')
有关如何以及为何需要POS标记的详细演示,请参阅https://www.kaggle.com/alvations/basic-nlp-with-nltk
或者,您可以使用pywsd
tokenizer + lemmatizer,这是NLTK WordNetLemmatizer
的包装器:
安装:
pip install -U nltk
python -m nltk.downloader popular
pip install -U pywsd
代码:
>>> from pywsd.utils import lemmatize_sentence
Warming up PyWSD (takes ~10 secs)... took 9.307677984237671 secs.
>>> text = "Mary leaves the room"
>>> lemmatize_sentence(text)
['mary', 'leave', 'the', 'room']
>>> text = 'Dew drops fall from the leaves'
>>> lemmatize_sentence(text)
['dew', 'drop', 'fall', 'from', 'the', 'leaf']