Pythonで文字列からストップワードを除去する

この記事では、Pythonで文字列からストップワードを除去するためのさまざまなテクニックを紹介します。

ストップワードとは、自然言語において「is」、「an」、「the」など、ほとんど意味を持たない単語のことです。

検索エンジンやその他の企業のインデックス作成プラットフォームは、ユーザーのクエリに対してデータベースから結果を取得する際に、しばしばストップワードをフィルタリングしています。

ストップワードは大量に発生するため、分類やクラスタリングに使用できる固有の情報をほとんど提供しないため、ディープラーニングや機械学習モデルをトレーニングする前にテキストからストップワードを除去することがよくあります。

Pythonによるストップワードの除去

Pythonプログラミング言語では、文字列からストップワードを除去するために、無数のオプションを使用することができます。

NLTK、SpaCy、Gensim、TextBlobなどの自然言語処理ライブラリのいずれかを使用することができますし、削除したいストップワードを完全に制御したい場合は、独自のカスタムスクリプトを記述することができます。

この記事では、使用しているNLPライブラリによって異なるアプローチをいくつか紹介します。

  • NLTKを使ったストップワード
  • Gensimを使ったストップワード
  • SpaCyによるストップワード

Python の NLTK ライブラリを使用する。

NLTKライブラリは、自然言語処理用のPythonライブラリとして最も古く、最もよく使われているライブラリの1つです。

NLTKはストップワードの除去をサポートしており、corpusモジュールでストップワードのリストを見つけることができます。

文章からストップワードを除去するには、テキストを単語に分割し、その単語がNLTKが提供するストップワードのリストに出ていれば除去することができる。

簡単な例を見てみましょう。

from nltk.corpus import stopwords
nltk.download('stopwords')
from nltk.tokenize import word_tokenize


text = "Nick likes to play football, however he is not too fond of tennis."
text_tokens = word_tokenize(text)


tokens_without_sw = [word for word in text_tokens if not word in stopwords.words()]


print(tokens_without_sw)


上のスクリプトでは、まず nltk.corpus モジュールから stopwords コレクションをインポートする。

次に、nltk.tokenize クラスから word_tokenize() メソッドをインポートします。

そして、簡単な文章を格納した変数 text を作成する。

変数 text に格納された文は、 word_tokenize() メソッドを用いてトークン化(単語に分割)される。

次に、text_tokens のリストにあるすべての単語を繰り返し処理し、その単語が stop words コレクションに存在するかどうかをチェックします。

ストップワードコレクションに単語が存在しない場合、その単語を返して tokens_without_sw リストに追加します。

そして、 tokens_without_sw のリストが表示される。

以下は、ストップワードがない場合の文の様子です。

['Nick', 'likes', 'play', 'football', ',', 'however', 'fond', 'tennis', '.']


この文から to, he, is, not, too という単語が削除されていることがわかります。

上記の単語のリストをつなぎ合わせると、以下のようにストップワードのない文章ができあがります。

filtered_sentence = (" ").join(tokens_without_sw)
print(filtered_sentence)


以下はその出力です。

Nick likes play football , however fond tennis .


NLTKのデフォルトのストップワードリストにストップワードを追加・削除する #### NLTKのデフォルトのストップワードリストにストップワードを追加・削除する

NLTKの既存のストップワードのコレクションに、お好みでストップワードを追加したり削除したりすることができます。

NLTKでストップワードを削除または追加する前に、NLTKがサポートするすべての英語のストップワードのリストを見てみましょう。

print(stopwords.words('english'))


出力します。

['i', 'me', 'my', 'myself', 'we', 'our', 'ours', 'ourselves', 'you', "you're", "you've", "you'll", "you'd", 'your', 'yours', 'yourself', 'yourselves', 'he', 'him', 'his', 'himself', 'she', "she's", 'her', 'hers', 'herself', 'it', "it's", 'its', 'itself', 'they', 'them', 'their', 'theirs', 'themselves', 'what', 'which', 'who', 'whom', 'this', 'that', "that'll", 'these', 'those', 'am', 'is', 'are', 'was', 'were', 'be', 'been', 'being', 'have', 'has', 'had', 'having', 'do', 'does', 'did', 'doing', 'a', 'an', 'the', 'and', 'but', 'if', 'or', 'because', 'as', 'until', 'while', 'of', 'at', 'by', 'for', 'with', 'about', 'against', 'between', 'into', 'through', 'during', 'before', 'after', 'above', 'below', 'to', 'from', 'up', 'down', 'in', 'out', 'on', 'off', 'over', 'under', 'again', 'further', 'then', 'once', 'here', 'there', 'when', 'where', 'why', 'how', 'all', 'any', 'both', 'each', 'few', 'more', 'most', 'other', 'some', 'such', 'no', 'nor', 'not', 'only', 'own', 'same', 'so', 'than', 'too', 'very', 's', 't', 'can', 'will', 'just', 'don', "don't", 'should', "should've", 'now', 'd', 'll', 'm', 'o', 're', 've', 'y', 'ain', 'aren', "aren't", 'couldn', "couldn't", 'didn', "didn't", 'doesn', "doesn't", 'hadn', "hadn't", 'hasn', "hasn't", 'haven', "haven't", 'isn', "isn't", 'ma', 'mightn', "mightn't", 'mustn', "mustn't", 'needn', "needn't", 'shan', "shan't", 'shouldn', "shouldn't", 'wasn', "wasn't", 'weren', "weren't", 'won', "won't", 'wouldn', "wouldn't"]


NLTKのデフォルトのストップワードリストにストップワードを追加する。

NLTKのストップワードコレクションに単語を追加するには、まず stopwords.words('english') リストからオブジェクトを作成します。

次に、そのリストの append() メソッドを用いて、任意の単語をリストに追加します。

次のスクリプトでは、playという単語をNLTKのストップワードコレクションに追加しています。

ここでも、変数 text からすべての単語を削除して、単語 play が削除されたかどうかを確認しています。

all_stopwords = stopwords.words('english')
all_stopwords.append('play')


text_tokens = word_tokenize(text)
tokens_without_sw = [word for word in text_tokens if not word in all_stopwords]


print(tokens_without_sw)


出力する。

['Nick', 'likes', 'football', ',', 'however', 'fond', 'tennis', '.']


出力は、playという単語が削除されたことを示している。

また、以下のように append メソッドを使用して、 stopwords.words リストに単語のリストを追加することができます。

sw_list = ['likes','play']
all_stopwords.extend(sw_list)


text_tokens = word_tokenize(text)
tokens_without_sw = [word for word in text_tokens if not word in all_stopwords]


print(tokens_without_sw)


上記のスクリプトでは、likesplayの2つの単語を stopwords.word リストに追加しています。

出力では、以下のように、この2つの単語は表示されません。

出力

['Nick', 'football', ',', 'however', 'fond', 'tennis', '.']


NLTKのデフォルトのストップワード一覧からストップワードを削除する。

stopwords.word(‘english’)は単なるアイテムのリストなので、他のリストと同じようにこのリストからアイテムを削除することができます。

最も簡単な方法は、remove()メソッドを使うことです。

これは、アプリケーションがストップワードが削除されないようにする必要がある場合に便利です。

例えば、ある文が否定されたときに、それを知るためにnot` という単語を文中に残しておく必要があるかもしれません。

次のスクリプトは、NLTKのデフォルトのストップワード一覧から、ストップワード not を削除するものです。

all_stopwords = stopwords.words('english')
all_stopwords.remove('not')


text_tokens = word_tokenize(text)
tokens_without_sw = [word for word in text_tokens if not word in all_stopwords]


print(tokens_without_sw)


出力

['Nick', 'likes', 'play', 'football', ',', 'however', 'not', 'fond', 'tennis', '.']


出力から、notという単語が入力文から削除されていないことがわかる。

Python の Gensim ライブラリを利用する

Gensim ライブラリも Python で文字列からストップワードを除去するのに非常に便利なライブラリです。

Gensim.parsing.preprocessingモジュールのremove_stopwords()メソッドをインポートすればよいのです。

次に、ストップワードを除去したい文章をremove_stopwords()` メソッドに渡すと、ストップワードを除いた文字列が返されます。

それでは、Gensim ライブラリを用いてストップワードを除去する簡単な例を見てみましょう。

from gensim.parsing.preprocessing import remove_stopwords


text = "Nick likes to play football, however he is not too fond of tennis."
filtered_sentence = remove_stopwords(text)


print(filtered_sentence)


出力

Nick likes play football, fond tennis.


ここで重要なのは、NLTKライブラリとGensimライブラリでストップワード除去後の出力が異なるということです。

例えば、Gensimライブラリはhoweverという単語をストップワードとみなしましたが、NLTKはそうではなかったため、削除されなかったのです。

このことから、ストップワードとそうでないものとの間に明確なルールは存在しないことがわかります。

それはすべて、あなたが行おうとしているタスクに依存するのです。

この後の章では、Gensim の既存のストップワードのコレクションにストップワードを追加したり削除したりする方法について説明します。

Gensim のデフォルトの Stop Words List に Stop Words を追加・削除する #### Gensim のデフォルトの Stop Words List に Stop Words を追加・削除する

まず、Python の Gensim ライブラリに含まれるストップワードについて見てみましょう。

import gensim
all_stopwords = gensim.parsing.preprocessing.STOPWORDS
print(all_stopwords)


を出力します。

frozenset({'her', 'during', 'among', 'thereafter', 'only', 'hers', 'in', 'none', 'with', 'un', 'put', 'hence', 'each', 'would', 'have', 'to', 'itself', 'that', 'seeming', 'hereupon', 'someone', 'eight', 'she', 'forty', 'much', 'throughout', 'less', 'was', 'interest', 'elsewhere', 'already', 'whatever', 'or', 'seem', 'fire', 'however', 'keep', 'detail', 'both', 'yourselves', 'indeed', 'enough', 'too', 'us', 'wherein', 'himself', 'behind', 'everything', 'part', 'made', 'thereupon', 'for', 'nor', 'before', 'front', 'sincere', 'really', 'than', 'alone', 'doing', 'amongst', 'across', 'him', 'another', 'some', 'whoever', 'four', 'other', 'latterly', 'off', 'sometime', 'above', 'often', 'herein', 'am', 'whereby', 'although', 'who', 'should', 'amount', 'anyway', 'else', 'upon', 'this', 'when', 'we', 'few', 'anywhere', 'will', 'though', 'being', 'fill', 'used', 'full', 'thru', 'call', 'whereafter', 'various', 'has', 'same', 'former', 'whereas', 'what', 'had', 'mostly', 'onto', 'go', 'could', 'yourself', 'meanwhile', 'beyond', 'beside', 'ours', 'side', 'our', 'five', 'nobody', 'herself', 'is', 'ever', 'they', 'here', 'eleven', 'fifty', 'therefore', 'nothing', 'not', 'mill', 'without', 'whence', 'get', 'whither', 'then', 'no', 'own', 'many', 'anything', 'etc', 'make', 'from', 'against', 'ltd', 'next', 'afterwards', 'unless', 'while', 'thin', 'beforehand', 'by', 'amoungst', 'you', 'third', 'as', 'those', 'done', 'becoming', 'say', 'either', 'doesn', 'twenty', 'his', 'yet', 'latter', 'somehow', 'are', 'these', 'mine', 'under', 'take', 'whose', 'others', 'over', 'perhaps', 'thence', 'does', 'where', 'two', 'always', 'your', 'wherever', 'became', 'which', 'about', 'but', 'towards', 'still', 'rather', 'quite', 'whether', 'somewhere', 'might', 'do', 'bottom', 'until', 'km', 'yours', 'serious', 'find', 'please', 'hasnt', 'otherwise', 'six', 'toward', 'sometimes', 'of', 'fifteen', 'eg', 'just', 'a', 'me', 'describe', 'why', 'an', 'and', 'may', 'within', 'kg', 'con', 're', 'nevertheless', 'through', 'very', 'anyhow', 'down', 'nowhere', 'now', 'it', 'cant', 'de', 'move', 'hereby', 'how', 'found', 'whom', 'were', 'together', 'again', 'moreover', 'first', 'never', 'below', 'between', 'computer', 'ten', 'into', 'see', 'everywhere', 'there', 'neither', 'every', 'couldnt', 'up', 'several', 'the', 'i', 'becomes', 'don', 'ie', 'been', 'whereupon', 'seemed', 'most', 'noone', 'whole', 'must', 'cannot', 'per', 'my', 'thereby', 'so', 'he', 'name', 'co', 'its', 'everyone', 'if', 'become', 'thick', 'thus', 'regarding', 'didn', 'give', 'all', 'show', 'any', 'using', 'on', 'further', 'around', 'back', 'least', 'since', 'anyone', 'once', 'can', 'bill', 'hereafter', 'be', 'seems', 'their', 'myself', 'nine', 'also', 'system', 'at', 'more', 'out', 'twelve', 'therein', 'almost', 'except', 'last', 'did', 'something', 'besides', 'via', 'whenever', 'formerly', 'cry', 'one', 'hundred', 'sixty', 'after', 'well', 'them', 'namely', 'empty', 'three', 'even', 'along', 'because', 'ourselves', 'such', 'top', 'due', 'inc', 'themselves'})


NLTKと比較して、Gensimのデフォルトのストップワード集は非常に詳細であることがわかります。

また、Gensimはデフォルトのストップワードをフローズンセットオブジェクトに格納しています。

Gensim のデフォルトの Stop Words リストに Stop Words を追加する。

Gensim のストップワード一覧にアクセスするには、gensim.parsing.preprocessong パッケージからフローズンセットである STOPWORDS をインポートする必要があります。

Python のフローズンセットとは、不変の集合の一種です。

フローズンセットでは、要素を追加したり削除したりすることはできません。

したがって、要素を追加するには、フローズンセットに union 関数を適用して、新しいストップワードの集合を渡す必要があります。

union` メソッドは、以下のように、新しく追加したストップワードが含まれる新しいセットを返します。

次のスクリプトでは、Gensim のストップワードに likesplay を追加しています。

from gensim.parsing.preprocessing import STOPWORDS


all_stopwords_gensim = STOPWORDS.union(set(['likes', 'play']))


text = "Nick likes to play football, however he is not too fond of tennis."
text_tokens = word_tokenize(text)
tokens_without_sw = [word for word in text_tokens if not word in all_stopwords_gensim]


print(tokens_without_sw)


出力

['Nick', 'football', ',', 'fond', 'tennis', '.']


上の出力から、likeplayがストップワードとして扱われ、結果として入力文から削除されたことがわかります。

デフォルトの Gensim Stopword リストからストップワードを取り除く

Gensim のストップワードリストからストップワードを削除するには、ストップワードリストを格納したフローズンセットオブジェクトに対して difference() メソッドを呼び出す必要があります。

difference()メソッドには、フローズンセットから削除したいストップワードのセットを渡す必要があります。

difference() メソッドは、 difference() メソッドに渡されたものを除くすべてのストップワードが含まれるセットを返します。

以下のスクリプトは、Gensim のストップワード集合から not という単語を削除するものです。

from gensim.parsing.preprocessing import STOPWORDS


all_stopwords_gensim = STOPWORDS
sw_list = {"not"}
all_stopwords_gensim = STOPWORDS.difference(sw_list)


text = "Nick likes to play football, however he is not too fond of tennis."
text_tokens = word_tokenize(text)
tokens_without_sw = [word for word in text_tokens if not word in all_stopwords_gensim]


print(tokens_without_sw)


出力

['Nick', 'likes', 'play', 'football', ',', 'not', 'fond', 'tennis', '.']


これで単語notがストップワード集合から取り除かれたので、ストップワード除去後の入力文から単語notが取り除かれていないことがわかります。

SpaCyライブラリの使用

PythonのSpaCyライブラリは、Pythonで自然言語処理を行うための非常に便利な言語です。

SpaCyをインストールするには、コマンドターミナルで以下のスクリプトを実行する必要があります。

$ pip install -U spacy


ライブラリをダウンロードしたら、言語モデルもダウンロードする必要があります。

SpaCyには言語ごとにいくつかのモデルが存在します。

ここでは、英語の言語モデルをインストールすることにします。

ターミナルで以下のコマンドを実行します。

$ python -m spacy download en


言語モデルのダウンロードが完了したら、SpaCyを使ってテキストからストップワードを削除することができます。

以下のスクリプトを見てください。

import spacy
sp = spacy.load('en_core_web_sm')


all_stopwords = sp.Defaults.stop_words


text = "Nick likes to play football, however he is not too fond of tennis."
text_tokens = word_tokenize(text)
tokens_without_sw= [word for word in text_tokens if not word in all_stopwords]


print(tokens_without_sw)


上のスクリプトでは、まず言語モデルをロードして、変数 sp に格納します。

sp.Default.stop_words`は、SpaCyの英語言語モデルのデフォルトのストップワード(単語)のセットです。

次に、入力テキストの各単語を単純に繰り返し、もしその単語がSpaCy言語モデルのストップワード集合に存在すれば、その単語は削除されます。

以下はその出力です。

出力は以下の通りです。

['Nick', 'likes', 'play', 'football', ',', 'fond', 'tennis', '.']


SpaCy デフォルトストップワードリストのストップワードの追加と削除

他のNLPライブラリと同様に、Spacyでもデフォルトのストップワードリストにストップワードを追加したり削除したりすることができます。

しかし、その前に、SpaCyに存在するすべてのストップワードのリストを見ます。

print(len(all_stopwords))
print(all_stopwords)


出力します。

326
{'whence', 'here', 'show', 'were', 'why', 'n’t', 'the', 'whereupon', 'not', 'more', 'how', 'eight', 'indeed', 'i', 'only', 'via', 'nine', 're', 'themselves', 'almost', 'to', 'already', 'front', 'least', 'becomes', 'thereby', 'doing', 'her', 'together', 'be', 'often', 'then', 'quite', 'less', 'many', 'they', 'ourselves', 'take', 'its', 'yours', 'each', 'would', 'may', 'namely', 'do', 'whose', 'whether', 'side', 'both', 'what', 'between', 'toward', 'our', 'whereby', "'m", 'formerly', 'myself', 'had', 'really', 'call', 'keep', "'re", 'hereupon', 'can', 'their', 'eleven', '’m', 'even', 'around', 'twenty', 'mostly', 'did', 'at', 'an', 'seems', 'serious', 'against', "n't", 'except', 'has', 'five', 'he', 'last', '‘ve', 'because', 'we', 'himself', 'yet', 'something', 'somehow', '‘m', 'towards', 'his', 'six', 'anywhere', 'us', '‘d', 'thru', 'thus', 'which', 'everything', 'become', 'herein', 'one', 'in', 'although', 'sometime', 'give', 'cannot', 'besides', 'across', 'noone', 'ever', 'that', 'over', 'among', 'during', 'however', 'when', 'sometimes', 'still', 'seemed', 'get', "'ve", 'him', 'with', 'part', 'beyond', 'everyone', 'same', 'this', 'latterly', 'no', 'regarding', 'elsewhere', 'others', 'moreover', 'else', 'back', 'alone', 'somewhere', 'are', 'will', 'beforehand', 'ten', 'very', 'most', 'three', 'former', '’re', 'otherwise', 'several', 'also', 'whatever', 'am', 'becoming', 'beside', '’s', 'nothing', 'some', 'since', 'thence', 'anyway', 'out', 'up', 'well', 'it', 'various', 'four', 'top', '‘s', 'than', 'under', 'might', 'could', 'by', 'too', 'and', 'whom', '‘ll', 'say', 'therefore', "'s", 'other', 'throughout', 'became', 'your', 'put', 'per', "'ll", 'fifteen', 'must', 'before', 'whenever', 'anyone', 'without', 'does', 'was', 'where', 'thereafter', "'d", 'another', 'yourselves', 'n‘t', 'see', 'go', 'wherever', 'just', 'seeming', 'hence', 'full', 'whereafter', 'bottom', 'whole', 'own', 'empty', 'due', 'behind', 'while', 'onto', 'wherein', 'off', 'again', 'a', 'two', 'above', 'therein', 'sixty', 'those', 'whereas', 'using', 'latter', 'used', 'my', 'herself', 'hers', 'or', 'neither', 'forty', 'thereupon', 'now', 'after', 'yourself', 'whither', 'rather', 'once', 'from', 'until', 'anything', 'few', 'into', 'such', 'being', 'make', 'mine', 'please', 'along', 'hundred', 'should', 'below', 'third', 'unless', 'upon', 'perhaps', 'ours', 'but', 'never', 'whoever', 'fifty', 'any', 'all', 'nobody', 'there', 'have', 'anyhow', 'of', 'seem', 'down', 'is', 'every', '’ll', 'much', 'none', 'further', 'me', 'who', 'nevertheless', 'about', 'everywhere', 'name', 'enough', '’d', 'next', 'meanwhile', 'though', 'through', 'on', 'first', 'been', 'hereby', 'if', 'move', 'so', 'either', 'amongst', 'for', 'twelve', 'nor', 'she', 'always', 'these', 'as', '’ve', 'amount', '‘re', 'someone', 'afterwards', 'you', 'nowhere', 'itself', 'done', 'hereafter', 'within', 'made', 'ca', 'them'}


この出力では、SpaCyライブラリのデフォルトのストップワードリストに326個のストップワードがあることがわかります。

デフォルトのSpaCy Stop WordsリストにStop Wordsを追加する

SpaCyのストップワードリストは基本的に文字列のセットです。

セットに新しいアイテムを追加するように、セットに新しい単語を追加することができます。

次のスクリプトでは、tennisという単語をSpacyの既存のストップワードリストに追加しています。

import spacy
sp = spacy.load('en_core_web_sm')


all_stopwords = sp.Defaults.stop_words
all_stopwords.add("tennis")


text = "Nick likes to play football, however he is not too fond of tennis."
text_tokens = word_tokenize(text)
tokens_without_sw = [word for word in text_tokens if not word in all_stopwords]


print(tokens_without_sw)


出力。

['Nick', 'likes', 'play', 'football', ',', 'fond', '.']


出力は、入力文からtennisという単語が削除されたことを示している。

また、以下のように複数の単語をSpaCyのストップワードリストに追加することができます。

次のスクリプトは likestennis をSpaCyのストップワードに追加しています。

import spacy
sp = spacy.load('en_core_web_sm')


all_stopwords = sp.Defaults.stop_words
all_stopwords |= {"likes","tennis",}


text = "Nick likes to play football, however he is not too fond of tennis."
text_tokens = word_tokenize(text)
tokens_without_sw = [word for word in text_tokens if not word in all_stopwords]


print(tokens_without_sw)


出力されます。

['Nick', 'play', 'football', ',', 'fond', '.']


出力は、入力文から likestennis の両方が削除されたことを示しています。

デフォルトのSpaCyストップワード一覧からストップワードを削除する

SpaCy の Stop Words のセットから単語を削除するには、セットの remove メソッドに削除したい単語を渡します。

次のスクリプトは not という単語をSpaCyのストップワードから削除します。

import spacy
sp = spacy.load('en_core_web_sm')


all_stopwords = sp.Defaults.stop_words
all_stopwords.remove('not')


text = "Nick likes to play football, however he is not too fond of tennis."
text_tokens = word_tokenize(text)
tokens_without_sw = [word for word in text_tokens if not word in all_stopwords]


print(tokens_without_sw)


出力

['Nick', 'play', 'football', ',', 'not', 'fond', '.']


出力では、入力文から単語notが削除されていないことがわかります。

カスタムスクリプトによるストップワードの除去

前のセクションでは、Pythonで文字列からストップワードを除去するために、様々なライブラリを使用する方法を見ました。

もし、ストップワードの除去を完全に制御したいのであれば、文字列からストップワードを除去する独自のスクリプトを書くことができます。

そのための最初のステップは、ストップワードとして扱われたい単語のリストを定義することです。

最もよく使われるストップワードのリストを作ってみましょう。

my_stopwords = ['i', 'me', 'my', 'myself', 'we', 'our', 'ours', 'ourselves', 'you', "you're", "you've", "you'll", "you'd", 'your', 'yours', 'yourself', 'yourselves', 'he', 'him', 'his', 'himself', 'she', "she's", 'her', 'hers', 'herself', 'it', "it's", 'its', 'itself', 'they', 'them', 'their', 'theirs', 'themselves', 'what', 'which', 'who', 'whom', 'this', 'that', "that'll", 'these', 'those', 'am', 'is', 'are', 'was', 'were', 'be', 'been', 'being', 'have', 'has', 'had', 'having', 'do', 'does', 'did', 'doing', 'a', 'an', 'the', 'and', 'but', 'if', 'or', 'because', 'as', 'until', 'while', 'of', 'at', 'by', 'for', 'with', 'about', 'against', 'between', 'into', 'through', 'during', 'before', 'after', 'above', 'below', 'to', 'from', 'up', 'down', 'in', 'out', 'on', 'off', 'over', 'under', 'again', 'further', 'then', 'once', 'here', 'there', 'when', 'where', 'why', 'how', 'all', 'any', 'both', 'each', 'few', 'more', 'most', 'other', 'some', 'such', 'no', 'nor', 'not', 'only', 'own', 'same', 'so', 'than', 'too', 'very', 's', 't', 'can', 'will', 'just', 'don', "don't", 'should', "should've", 'now', 'd', 'll', 'm', 'o', 're', 've', 'y', 'ain', 'aren', "aren't", 'couldn', "couldn't", 'didn', "didn't", 'doesn', "doesn't", 'hadn', "hadn't", 'hasn', "hasn't", 'haven', "haven't", 'isn', "isn't", 'ma', 'mightn', "mightn't", 'mustn', "mustn't", 'needn', "needn't", 'shan', "shan't", 'shouldn', "shouldn't", 'wasn', "wasn't", 'weren', "weren't", 'won', "won't", 'wouldn', "wouldn't"]


次に、文字列をパラメータとして受け取り、ストップワードを除いた文章を返す関数を定義します。

def remove_mystopwords(sentence):
    tokens = sentence.split(" ")
    tokens_filtered= [word for word in text_tokens if not word in my_stopwords]
    return (" ").join(tokens_filtered)


それでは、サンプル文からストップワードを除去してみましょう。

text = "Nick likes to play football, however he is not too fond of tennis."
filtered_text = remove_mystopwords(text)
print(filtered_text)


出力

Nick likes play , however fond tennis .


my_stopwords` リストにあるストップワードが、入力文から削除されていることがわかります。

my_stopwordsリストは単純な文字列のリストなので、そこに単語を追加したり削除したりすることができる。

例えば、my_stopwordsのリストにfootball` という単語を追加し、再び入力文からストップワードを除去してみよう。

text = "Nick likes to play football, however he is not too fond of tennis."
filtered_text = remove_mystopwords(text)
print(filtered_text)


出力する。

Nick likes play , however fond tennis .


出力は、カスタムストップワードのリストに単語 football を追加したので、入力文から単語 football が削除されたことを示しています。

では、停止語のリストからfootballという単語を削除して、再び入力文に停止語除去を適用してみましょう。

my_stopwords.remove("football")


text = "Nick likes to play football, however he is not too fond of tennis."
filtered_text = remove_mystopwords(text)
print(filtered_text)


出力

Nick likes play football , however fond tennis .


football`という単語は、ストップワードのリストから取り除いたので、今は取り除かれていません。

結論

この記事では、Pythonで文字列からストップワードを削除するために使用できるさまざまなライブラリについて見ました。

また、様々なライブラリが提供するデフォルトのストップワードのリストから、ストップワードを追加または削除する方法についても説明しました。

最後に、ストップワードを除去するためのカスタムスクリプトがある場合、これをどのように実行するかを示しました。

タイトルとURLをコピーしました