Python-data-science-python-stemming-and-lemmatization

提供:Dev Guides
移動先:案内検索

Python-ステミングと補題

自然言語処理の分野では、2つ以上の単語が共通の語根を持つ状況に遭遇します。 たとえば、同意、同意、同意の3つの単語は、同じ語根が一致します。 これらの単語のいずれかを含む検索では、それらをルート単語である同じ単語として扱う必要があります。 そのため、すべての単語をルート単語にリンクすることが不可欠になります。 NLTKライブラリには、このリンクを実行し、ルートワードを示す出力を提供するメソッドがあります。

以下のプログラムは、ステミングにポーターステミングアルゴリズムを使用しています。

import nltk
from nltk.stem.porter import PorterStemmer
porter_stemmer = PorterStemmer()

word_data = "It originated from the idea that there are readers who prefer learning new skills from the comforts of their drawing rooms"
# First Word tokenization
nltk_tokens = nltk.word_tokenize(word_data)
#Next find the roots of the word
for w in nltk_tokens:
       print "Actual: %s  Stem: %s"  % (w,porter_stemmer.stem(w))

上記のコードを実行すると、次の結果が生成されます。

Actual: It  Stem: It
Actual: originated  Stem: origin
Actual: from  Stem: from
Actual: the  Stem: the
Actual: idea  Stem: idea
Actual: that  Stem: that
Actual: there  Stem: there
Actual: are  Stem: are
Actual: readers  Stem: reader
Actual: who  Stem: who
Actual: prefer  Stem: prefer
Actual: learning  Stem: learn
Actual: new  Stem: new
Actual: skills  Stem: skill
Actual: from  Stem: from
Actual: the  Stem: the
Actual: comforts  Stem: comfort
Actual: of  Stem: of
Actual: their  Stem: their
Actual: drawing  Stem: draw
Actual: rooms  Stem: room

語彙化は類似した語幹解析ですが、単語のコンテキストをもたらします。 たとえば、段落に車、電車、自動車などの単語がある場合、それらはすべて自動車にリンクされます。 以下のプログラムでは、語彙化にWordNet語彙データベースを使用します。

import nltk
from nltk.stem import WordNetLemmatizer
wordnet_lemmatizer = WordNetLemmatizer()

word_data = "It originated from the idea that there are readers who prefer learning new skills from the comforts of their drawing rooms"
nltk_tokens = nltk.word_tokenize(word_data)
for w in nltk_tokens:
       print "Actual: %s  Lemma: %s"  % (w,wordnet_lemmatizer.lemmatize(w))

上記のコードを実行すると、次の結果が生成されます。

Actual: It  Lemma: It
Actual: originated  Lemma: originated
Actual: from  Lemma: from
Actual: the  Lemma: the
Actual: idea  Lemma: idea
Actual: that  Lemma: that
Actual: there  Lemma: there
Actual: are  Lemma: are
Actual: readers  Lemma: reader
Actual: who  Lemma: who
Actual: prefer  Lemma: prefer
Actual: learning  Lemma: learning
Actual: new  Lemma: new
Actual: skills  Lemma: skill
Actual: from  Lemma: from
Actual: the  Lemma: the
Actual: comforts  Lemma: comfort
Actual: of  Lemma: of
Actual: their  Lemma: their
Actual: drawing  Lemma: drawing
Actual: rooms  Lemma: room