PythonとNLTKでストップワードを除去する方法【サンプルコード付き解説】
自然言語処理(NLP)の基本的な考え方は、機械が少なくともある程度まで人間の介入なしにテキストの分析や処理を行えるようにするというものです。たとえば、テキストが何を意味しているのか、あるいは何を伝えようとしているのかを部分的に理解することなどが挙げられます。
テキストを処理する際、コンピュータは文章の中から不要なデータ(単語)や重要度の低いデータを取り除く必要があります。NLTKでは、このような役に立たない単語(データ)のことをストップワードと呼びます。これらを事前に除去しておくことで、データベースの容量を節約できるだけでなく、貴重な処理時間の浪費も防ぐことができます。
必要なライブラリのインストール
まず、nltkライブラリが必要です。ターミナルで以下のコマンドを実行してインストールしてください。
$pip install nltk
また、トークン化を行うために punkt データが必要になる場合があります。あらかじめダウンロードしておくと安心です。
>>> import nltk
>>> nltk.download('punkt')
NLTK標準のストップワード一覧
ストップワードとして扱う単語のリストは、自分で独自に作成することも可能です。ただし、デフォルトのNLTKには、すでにストップワードとみなされる単語が多数含まれています。NLTKコーパスからは以下のようにアクセスできます。
>>> import nltk >>> from nltk.corpus import stopwords
以下が、NLTKに含まれる英語のストップワードの一覧です。
>>> set(stopwords.words('english'))
{'not', 'other', 'shan', "hadn't", 'she', 'did', 'through', 'and', 'does', "that'll", "weren't", 'your', "should've", "hasn't", 'myself', 'should', 'because', 'wasn', 'what', 'to', 'this', 'was', 'more', 'y', 'again', "needn't", 'into', 'above', 'themselves', 'd', "won't", 'during', 'haven', 'both', "shan't", 'their', 'on', 'hadn', 'up', 'once', 'its', 'against', 'before', 't', 'while', 'needn', 'doing', "don't", 'yourselves', 'until', 'is', 'all', 's', 'will', "you've", 'being', 'under', 'they', 'ours', 'wouldn', 'of', 'didn', 'below', 'just', 'ma', 'yours', "you'll", 'mightn', 'where', 'are', 'that', 'those', 'most', 'them', 'if', 'you', "shouldn't", 'off', 'for', 'her', 'such', 'now', 'than', 're', 'no', 'm', 'or', "aren't", 'further', 'here', "wasn't", 'after', "haven't", 'my', 'himself', 'at', 'had', 'yourself', 'by', 'weren', 'only', 'have', 'we', 'do', 'same', "isn't", 'herself', 'll', 'down', 'then', 'why', 'own', 'him', 'so', 'having', 'nor', 'isn', 'few', 'how', 'each', 'there', 'with', 'couldn', 'about', 'very', 'am', 'me', "didn't", "doesn't", 'which', "she's", 'doesn', 'were', 'he', 'in', "mightn't", 'when', 'our', 'who', 'his', "couldn't", 'the', "you'd", 'be', 'hers', 'hasn', 'between', 'it', 'mustn', 'but', 'out', 'can', "wouldn't", 'ourselves', 'whom', 'been', 'these', 'aren', 'over', 'itself', 'a', 'i', 'too', 'theirs', 'some', "you're", 'as', 'won', "it's", 'from', 'o', 'don', 'any', 've', 'ain', 'has', 'an', "mustn't", 'shouldn'}
サンプルコード:ストップワードを除去するプログラム
以下は、ストップワードを使ってテキストから不要な単語を除去する方法を示す、完全なサンプルプログラムです。word_tokenizeで文章を単語に分割し、その中からストップワードに該当しない単語だけを新しいリストに追加しています。
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
example_sent = "Python is a powerful high-level, object-oriented programming language created by Guido van Rossum."\
"It has simple easy-to-use syntax, making it the perfect language for someone trying to learn computer programming for the first time."\
"This is a comprehensive guide on how to get started in Python, why you should learn it and how you can learn it. However, if you knowledge "\
"of other programming languages and want to quickly get started with Python."
stop_words = set(stopwords.words('english'))
word_tokens = word_tokenize(example_sent)
filtered_sentence = []
for w in word_tokens:
if w not in stop_words:
filtered_sentence.append(w)
print(word_tokens)
print(filtered_sentence)
なお、リスト内包表記を使えば、同じ処理をより簡潔に1行で書くこともできます。
filtered_sentence = [w for w in word_tokens if not w in stop_words]
実行結果
フィルタ前の出力(ストップワードが残っている状態)
['Python', 'is', 'a', 'powerful', 'high-level', ',', 'object-oriented', 'programming', 'language', 'created', 'by', 'Guido', 'van', 'Rossum.It', 'has', 'simple', 'easy-to-use', 'syntax', ',', 'making', 'it', 'the', 'perfect', 'language', 'for', 'someone', 'trying', 'to', 'learn', 'computer', 'programming', 'for', 'the', 'first', 'time.This', 'is', 'a', 'comprehensive', 'guide', 'on', 'how', 'to', 'get', 'started', 'in', 'Python', ',', 'why', 'you', 'should', 'learn', 'it', 'and', 'how', 'you', 'can', 'learn', 'it', '.', 'However', ',', 'if', 'you', 'knowledge', 'of', 'other', 'programming', 'languages', 'and', 'want', 'to', 'quickly', 'get', 'started', 'with', 'Python', '.']
フィルタ後の出力(ストップワード除去済み)
['Python', 'powerful', 'high-level', ',', 'object-oriented', 'programming', 'language', 'created', 'Guido', 'van', 'Rossum.It', 'simple', 'easy-to-use', 'syntax', ',', 'making', 'perfect', 'language', 'someone', 'trying', 'learn', 'computer', 'programming', 'first', 'time.This', 'comprehensive', 'guide', 'get', 'started', 'Python', ',', 'learn', 'learn', '.', 'However', ',', 'knowledge', 'programming', 'languages', 'want', 'quickly', 'get', 'started', 'Python', '.']
実行結果を見ると、「is」「a」「the」「to」「and」などの一般的すぎる単語が取り除かれ、「Python」「programming」「language」など、テキストの意味を左右する重要な語だけが残っていることがわかります。このようにストップワード除去は、検索エンジンの索引作成やテキスト分類など、さまざまな自然言語処理タスクの前処理として非常に有効な手法です。
-
Pythonで最大の成功確率を持つパスを見つけるプログラムの実装方法
問題の概要 n 個のノード(ノードには 0 から順に番号が振られています)からなる無向重み付きグラフを考えます。このグラフは辺リスト(edge list)として入力され、各辺 e には「その辺を通過する際の成功確率」probability[e] が割り当てられています。さらに、開始ノード(start)と終了ノード(end)も与えられます。 求めたいのは、start から end へ移動するときに成功確率が最大となる経路であり、答えとしてその成功確率を返します。経路がひとつも存在しない場合は 0 を返してください。 たとえば、次のような入力が与えられたとします。 この場合の出力は 0.25
-
PythonのpylabでFigureをリモート環境に保存する方法
概要matplotlibのpyplotパッケージが提供するsavefig()メソッドを使えば、保存先のパスを指定するだけで、Figure(グラフ)をリモート環境に保存できます。GUIを持たないサーバーやクラウド環境でグラフを生成・保存したい場合に特に便利な手法です。手順別のバックエンドを使用するには、matplotlib.use(Agg)でバックエンドを明示的に設定します。plot()メソッドを使って線をプロットします。savefig()メソッドを使い、保存先のディレクトリ(パス)を指定するだけで、画像をリモート環境に保存できます。図を画面に表示したい場合は、plt.show()を使用します。