基本的なNLTK
NLTKを使う上での基本的なステップ、よく使用されるメソッドとクラス
基本的なステップ:
a. インストールとインポート
pip install nltk
import nltk
b. 必要なデータのダウンロード
pythonCopynltk.download('punkt')
nltk.download('averaged_perceptron_tagger')
nltk.download('stopwords')
NLTKは多くの自然言語処理タスクを実行するために、様々な言語データや学習済みモデルを必要とします。これらのデータは、サイズが大きく、ライブラリ本体に含めると配布サイズが膨大になってしまうため、必要に応じて別途ダウンロードする設計になっています。
何をダウンロードしているのか?
例として挙げた3つのダウンロード項目について説明します:
a.
nltk.download('punkt')
Punkt Sentence Tokenizerをダウンロードします。
これは、テキストを文単位に分割するためのモデルです。
b.
nltk.download('averaged_perceptron_tagger')
品詞タグ付けのための学習済みモデルをダウンロードします。
c.
nltk.download('stopwords')
様々な言語のストップワード(冠詞、前置詞など、頻出するが意味的な重要性が低い単語)のリストをダウンロードします。
a. Punkt Sentence Tokenizer:
sent_tokenize() 関数で使用されます。
テキストを文単位に正確に分割するのに役立ちます。
例:
pythonCopyfrom nltk.tokenize import sent_tokenize
text = "Hello world. How are you? I'm fine, thanks."
sentences = sent_tokenize(text)
# 結果: ['Hello world.', 'How are you?', "I'm fine, thanks."]
b. Averaged Perceptron Tagger:
pos_tag() 関数で使用されます。
単語に品詞タグを付けるのに使います。
例:
pythonCopyfrom nltk import word_tokenize, pos_tag
text = "John likes to play basketball"
tokens = word_tokenize(text)
tagged = pos_tag(tokens)
# 結果: [('John', 'NNP'), ('likes', 'VBZ'), ('to', 'TO'), ('play', 'VB'), ('basketball', 'NN')]
c. Stopwords:
ストップワードのリストを取得するのに使用されます。
テキスト分析や検索エンジンなどで、重要でない単語を除去するのに役立ちます。
例:
pythonCopyfrom nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
text = "This is a sample sentence, showing off the stop words filtration."
stop_words = set(stopwords.words('english'))
words = word_tokenize(text)
filtered_sentence = [w for w in words if not w.lower() in stop_words]
# 結果: ['This', 'sample', 'sentence', ',', 'showing', 'stop', 'words', 'filtration', '.']
これらのデータや学習済みモデルをダウンロードすることで、NLTKは高度な自然言語処理タスクを正確に実行できるようになります。データのダウンロードは初回のみ必要で、一度ダウンロードしたデータは保存され、以降の実行時に再利用されます。
プロジェクトの要件に応じて、他にも多くの種類のデータや学習済みモデルをダウンロードできます。nltk.download() を引数なしで実行すると、利用可能なすべてのパッケージのリストが表示されます。
よく使用されるメソッドとクラス:
a. テキストの分割(トークン化)
pythonCopyfrom nltk.tokenize import word_tokenize, sent_tokenize
text = "This is a sample sentence. This is another one."
words = word_tokenize(text)
sentences = sent_tokenize(text)
b. ストップワードの除去
pythonCopyfrom nltk.corpus import stopwords
stop_words = set(stopwords.words('english'))
filtered_words = [word for word in words if word.lower() not in stop_words]
c. 品詞タグ付け
pythonCopyfrom nltk import pos_tag
tagged_words = pos_tag(words)
d. ステミング(語幹抽出)
pythonCopyfrom nltk.stem import PorterStemmer
stemmer = PorterStemmer()
stemmed_words = [stemmer.stem(word) for word in words]
e. レンマ化
pythonCopyfrom nltk.stem import WordNetLemmatizer
lemmatizer = WordNetLemmatizer()
lemmatized_words = [lemmatizer.lemmatize(word) for word in words]
f. 固有表現抽出
pythonCopyfrom nltk import ne_chunk
nltk.download('maxent_ne_chunker')
nltk.download('words')
named_entities = ne_chunk(tagged_words)
g. 頻度分析
pythonCopyfrom nltk import FreqDist
fdist = FreqDist(words)
most_common = fdist.most_common(10) # 上位10個の頻出語
h. コロケーション(共起)分析
pythonCopyfrom nltk.collocations import BigramCollocationFinder
bigram_measures = nltk.collocations.BigramAssocMeasures()
finder = BigramCollocationFinder.from_words(words)
collocations = finder.nbest(bigram_measures.pmi, 10) # 上位10個のコロケーション
i. テキスト分類(Naive Bayes分類器の例)
pythonCopyfrom nltk.classify import NaiveBayesClassifier
from nltk.classify.util import accuracy
トレーニングデータの準備
train_data = [
({'word': 'excellent'}, 'positive'),
({'word': 'terrible'}, 'negative'),
# ... 他のトレーニングデータ
]
classifier = NaiveBayesClassifier.train(train_data)
これらは、NLTKを使用する際の基本的なステップとよく使用されるメソッド・クラスの一部です。実際のプロジェクトでは、これらを組み合わせたり、より高度な機能を使用したりすることになります。
NLTKは非常に豊富な機能を持っているため、公式ドキュメントやチュートリアルを参照しながら、プロジェクトの要件に応じて適切な機能を選択し使用することをお勧めします。また、実際にコードを書いて実行しながら、各機能の動作を確認することが理解を深める上で非常に効果的です。
この記事が気に入ったらサポートをしてみませんか?