编程语言
首页 > 编程语言> > python – nltk:如何将周围的单词引入上下文?

python – nltk:如何将周围的单词引入上下文?

作者:互联网

以下代码打印出leaf:

from nltk.stem.wordnet import WordNetLemmatizer

lem = WordNetLemmatizer()
print(lem.lemmatize('leaves'))

取决于周围环境,这可能是也可能不准确,例如,玛丽离开房间,而露滴从树叶上落下.我怎样才能告诉NLTK将周围环境考虑在内的单词?

解决方法:

TL; DR

首先标记句子,然后使用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']

标签:python,machine-learning,nlp,nltk,lemmatization
来源: https://codeday.me/bug/20191002/1843016.html