のび〜る文字
感情分析に戻りましょう。次のタスクは、ツイート内に現れる引き伸ばされた単語を置換することです。ここでは、同じ文字が2回以上連続して現れる単語を引き伸ばされた単語と定義します(例: "Awesoooome")。
これらの単語を置換するのはとても重要です。なぜなら、分類器は元の単語とは別の用語として扱ってしまい、出現頻度が下がってしまうからです。
それらを見つけるために、キャプチャグループを使い、数字で参照します(例 \4)。
例えば Awesoooome にマッチさせたい場合、まず Awes をキャプチャし、次に o にマッチさせて同じ文字を参照し、その後に me をマッチさせます。
3つのツイート本文を含むリスト sentiment_analysis と、re モジュールはすでに読み込まれています。IPython Shell で print() を使えばデータを確認できます。
この演習はコースの一部です
Pythonで学ぶ正規表現
演習の手順
- 説明どおり、引き伸ばされた単語にマッチする正規表現を完成させてください。
sentiment_analysisリストの各要素を検索し、引き伸ばされた単語が含まれるかを確認しなさい。結果をmatch_elongatedに代入します。- キャプチャグループ番号0を変数
elongated_wordに代入します。 - 変数
elongated_wordに入っている結果を出力してください。
実践的なインタラクティブ演習
このサンプルコードを完成させて、この演習に挑戦してみましょう。
# Complete the regex to match an elongated word
regex_elongated = r"____(____)____\w*"
for tweet in sentiment_analysis:
# Find if there is a match in each tweet
match_elongated = re.____(____, ____)
if match_elongated:
# Assign the captured group zero
elongated_word = match_elongated.____(____)
# Complete the format method to print the word
print("Elongated word found: {____}".format(word=____))
else:
print("No elongated word found")