WordCloud入門

業務でとったアンケートの分析を可視化したくて、WordCloudに挑戦しました。

WordCloudとは

WordCloudとは、テキスト中に出現する単語を出現頻度に比例して散りばめた画像を作成するツールです。 下のサンプルはオンライン英会話のメモをWordCloudに入力した結果です。ビジネス系の英会話メモなのでビジネスに関係する用語が多数、大きく表示されていますね。

f:id:applepolish503:20211204114821p:plain
WordCloudの出力

つくるもの

pythonスクリプトと同じフォルダに入れた英語の文章をWordCloudで解析し文章中に頻出する単語を可視化します。私の目的である日本語の文章解析はプラスアルファの作業が必要なため、別の記事で紹介します。

WordCloudのインストール

自宅のMac環境ではpipコマンドで一発でインストールできました。

# pip install wordcloud

会社のWindows環境で同コマンドを実行したところ、エラーがでてインストールできなかったため、以下の記事を参考にインストールしました。

www.edureka.co

  1. 自分のPythonWindows環境(32bit or 64bit)に適合する .whl ファイルをここからダウンロードする
  2. コマンドプロンプトでダウンロードしたパスに移動する
  3. コマンドを実行する # py -<python version> -m pip install <filename.whl>

コード全体

# Import packages and modules
import matplotlib.pyplot as plt
from wordcloud import WordCloud, STOPWORDS
import sys, os


# Read text
os.chdir(sys.path[0])
text = open('cloud.txt', mode='r', encoding='utf-8').read()


# Generate WordCloud object
stopwords = {'Will','Yasu'}
stopwords |= STOPWORDS
wc = WordCloud(
    background_color='black',
    stopwords=stopwords,
    font_path=r"/System/Library/Fonts/ヒラギノ角ゴシック W6.ttc",
    height = 600,
    width=600
)

wc.generate(text)

# Write to image file
wc.to_file('result.png')

コード解説

公式ドキュメント

公式ドキュメントはこちら

パッケージとモジュールのインポート

# Import packages and modules
import matplotlib.pyplot as plt
from wordcloud import WordCloud, STOPWORDS
import sys, os

matplotlib.pyplotはWordCloudで解析した結果を画像化するのに使います。

WordCloudワードクラウドの生成、描画用のクラスです。

STOPWORDS自然言語をコンピュータで処理するときに処理対象外とする英単語の集合(set)です。

print()で中身を見ると{'such', 'down', 'into', "i'll", "i've", 'himself'...}のようにどんな文章でも出てきそうな一般的な単語が格納されています。

sysはパスの取得、osディレクトリの移動に使っており、WordCloudの利用には必須ではありません。

テキストの読み込み

# Read text
os.chdir(sys.path[0])
text = open('cloud.txt', mode='r', encoding='utf-8').read()

os.chdir(sys.path[0])pythonスクリプトがあるフォルダをカレントディレクトリにします。

sys.path[0]Python インタプリタを起動したスクリプトのあるディレクトリの文字列です。

open('cloud.txt', mode='r', encoding='utf-8').read()でカレントディレクトリのcloud.txtを読込みます。

WordCloudオブジェクトの生成

# Generate WordCloud object
stopwords = {'Will','Yasu'}
stopwords |= STOPWORDS
wc = WordCloud(
    background_color='black',
    stopwords=stopwords,
    font_path=r"/System/Library/Fonts/ヒラギノ角ゴシック W6.ttc",
    height = 600,
    width=600
)

wc.generate(text)

自作のストップワードのsetを作成し、STOPWORDSと結合します。 ちなみにYasuはオンライン英会話のロールプレイに頻出する人名です。

stopwords = {'Will','Yasu'}
stopwords |= STOPWORDS

wc = WordCloud()にはオブジェクト生成時のオプションをしています。

font_path=rrは文字リテラル内のエスケープシーケンスを展開しない(raw文字列にする)という意味です。

wc.generate(text)で読み込んだテキストのWordCloudを生成します。

イメージファイルへの書き込み

私の環境(MacBook Pro 2019 2.8Ghz Core i7)では、2000行の英文テキストを数秒で画像化できました。

# Write to image file
wc.to_file('result.png')

結果

冒頭の画像に比べて、追加したstopwordsが除外されています。

f:id:applepolish503:20211204130022p:plain
WordCloudの出力(STOPWORDS追加)