テキストのクリーニング

Pythonで学ぶNLPの特徴量エンジニアリング

Rounak Banik

Data Scientist

テキストのクリーニング手法

  • 不要な空白・エスケープシーケンス
  • 句読点
  • 特殊文字(数字、絵文字など)
  • ストップワード
Pythonで学ぶNLPの特徴量エンジニアリング

isalpha()

"Dog".isalpha()
True
"3dogs".isalpha()
False
"12347".isalpha()
False
"!".isalpha()
False
"❤".isalpha()
False
Pythonで学ぶNLPの特徴量エンジニアリング

注意点

  • 略語: U.S.AU.K など
  • 固有名詞: word2vecxto10x
  • 微妙なケースは正規表現で独自関数を作成
Pythonで学ぶNLPの特徴量エンジニアリング

非アルファベット文字の除去

string = """
OMG!!!! This is like    the best thing ever \t\n. 
Wow, such an amazing song! I'm hooked. Top 5 definitely. ❤
"""

import spacy # トークンのリストを生成 nlp = spacy.load('en_core_web_sm') doc = nlp(string) lemmas = [token.lemma_ for token in doc]
Pythonで学ぶNLPの特徴量エンジニアリング

非アルファベット文字の除去

...
...
# アルファベット以外のトークンを除去
a_lemmas = [lemma for lemma in lemmas 
            if lemma.isalpha() or lemma == '-PRON-']

# クリーニング後の文字列を出力 print(' '.join(a_lemmas))
'omg this be like the good thing ever wow such an amazing song -PRON- be hooked top definitely'
Pythonで学ぶNLPの特徴量エンジニアリング

ストップワード

  • 非常に頻出する語
  • 例: 冠詞、be動詞、代名詞など
Pythonで学ぶNLPの特徴量エンジニアリング

spaCyでストップワードを除去

# ストップワードの取得
stopwords = spacy.lang.en.stop_words.STOP_WORDS

string = """ OMG!!!! This is like the best thing ever \t\n. Wow, such an amazing song! I'm hooked. Top 5 definitely. ❤ """
Pythonで学ぶNLPの特徴量エンジニアリング

spaCyでストップワードを除去

...
...
# ストップワードと非アルファベットを除去
a_lemmas = [lemma for lemma in lemmas 
            if lemma.isalpha() and lemma not in stopwords]
# クリーニング後の文字列を出力
print(' '.join(a_lemmas))
'omg like good thing wow amazing song hooked definitely'
Pythonで学ぶNLPの特徴量エンジニアリング

その他の前処理手法

  • HTML/XMLタグの除去
  • アクセント文字の置換(例: é)
  • スペルミスの補正
Pythonで学ぶNLPの特徴量エンジニアリング

注意点

アプリケーションに必要な前処理だけを実施してください。

Pythonで学ぶNLPの特徴量エンジニアリング

Passons à la pratique !

Pythonで学ぶNLPの特徴量エンジニアリング

Preparing Video For Download...