Pynote

Python、機械学習、画像処理について

Python - Word Cloud を作成する方法について

Word Cloud とは

wordcloud ライブラリ

wordcloud は、matplotlib を利用して Word Cloud を作成できる Python ライブラリである。

基本的な使い方

import this で表示される 「The Zen of Python」の Word Cloud を作成する。

import numpy as np
from wordcloud import WordCloud

text = """The Zen of Python, by Tim Peters
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!"""

WordCloud オブジェクトを作成し、generate() にテキストを渡すことでワードクラウドが作成される。
生成した画像は to_file(filepath) でファイルに保存するか、to_array() で numpy 配列として取得できる。

wordcloud = WordCloud(width=480, height=320)

# テキストからワードクラウドを生成する。
wordcloud.generate(text)

# ファイルに保存する。
wordcloud.to_file('wordcloud.png')

# numpy 配列で取得する。
img = wordcloud.to_array()


WordCloud クラス

WordCloud クラスのコンストラクタ引数で生成する Word Cloud の見た目や大きさなどを調整できる。

  • width: 幅。
  • height: 高さ。
  • prefer_horizontal: 文字を横方向に表示する割合。1に近いほど横方向、0に近いほど縦方向の文字の割合が増える。
  • mask: マスク。
    • [255, 255, 255] でない画素にのみ文字を描画する。
    • これを指定した場合、width, height の値は無視される。
  • contour_width: マスクの輪郭を描画する際の幅。0の場合、輪郭を描画しない。
  • contour_color: 輪郭を描画する際の色。
  • scale: スケール。(width * scale, height * scale) が最終的に出力される画像サイズとなる。
  • font_step: 文字の密集度合い。1以上の float で指定する。大きい値ほどレイアウトは疎になる。
  • max_words: 描画する単語数の最大値。
  • stopwords: 描画対象から除外する単語一覧。
  • background_color: 背景色。
  • mode: 'RGB' または 'RGBA' を指定する。
  • relative_scaling: 単語の出現数とフォントサイズの関係。[0, 1] の float で指定する。
  • color_func: 色を返すコールバック関数。
  • regexp: 入力の文字列を分割する際の区切り文字。
  • colormap: カラーマップ
  • collocations: 連語を1語ずつ扱うかどうか。
  • normalize_plurals: 複数形はすべて単数形に直して扱う。
  • repeat: 同じ単語を複数回描画するかどうか。

背景色を変更する。

# 背景を白にする。
wordcloud = WordCloud(width=480, height=320,
                      background_color='white')

wordcloud.generate(text)
wordcloud.to_file('wordcloud.png')

Word Cloud から除外する単語を設定する。

デフォルトでは、STOPWORDS で定義されている人称代名詞、接続詞などの単語は Word Cloud の描画対象から除外されている。

from wordcloud import STOPWORDS, WordCloud

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

stopwords 引数に set() で単語の一覧を渡すことで除外する単語を指定できる。

text = 'banana apple orange'

# orange は Word Cloud から除く。
wordcloud = WordCloud(width=480, height=320,
                      stopwords={'orange'})

wordcloud.generate(text)
wordcloud.to_file('wordcloud.png')


カラーマップを指定する。

指定できるカラーマップの一覧は以下を参照。

http://pynote.hatenablog.com/entry/matplotlib-colorpynote.hatenablog.com

wordcloud = WordCloud(width=480, height=320,
                      background_color='white', colormap='winter')

wordcloud.generate(text)
wordcloud.to_file('wordcloud.png')


単語一覧の指定方法

generate(text) に文章をそのまま渡す方法と、fit_words(words) に単語がキー、出現頻度が値となった辞書を渡す方法がある。

wordcloud = WordCloud(width=480, height=320, background_color='white')

# 文章を渡す。
text = 'banana apple orange'
wordcloud.generate(text)
wordcloud.to_file('wordcloud.png')

# 単語がキー、出現頻度が値となった辞書を渡す。
words = {'banana': 0.2, 'apple': 0.4, 'orange': 0.7}
wordcloud.fit_words(words)
wordcloud.to_file('wordcloud.png')


マスクを使用する。

マスクを使用することで画像全体でなく、一部にのみ単語を描画することができる。
mask 引数には (height, width, 3) の文字を描画しない領域の値を [255, 255, 255] にした3次元配列を渡す。
生成される画像サイズは mask と同じ (width, height) になる。
マスクとそれ以外の輪郭線の幅を contour_width、色を contour_color で指定できる。
輪郭線を描画しない場合は contour_width=0 とする。

使用するマスク画像

from PIL import Image
from wordcloud import WordCloud

text = 'square'

# マスクを読み込む。
mask = np.array(Image.open('wordcloud_07.png'))

# 文章
text = '''Alice was beginning to get very tired of sitting by her sister on the bank, and of having nothing to do: once or twice she had peeped into the book her sister was reading, but it had no pictures or conversations in it, `and what is the use of a book,' thought Alice `without pictures or conversation?'
So she was considering in her own mind (as well as she could, for the hot day made her feel very sleepy and stupid), whether the pleasure of making a daisy-chain would be worth the trouble of getting up and picking the daisies, when suddenly a White Rabbit with pink eyes ran close by her.
There was nothing so very remarkable in that; nor did Alice think it so very much out of the way to hear the Rabbit say to itself, `Oh dear! Oh dear! I shall be late!' (when she thought it over afterwards, it occurred to her that she ought to have wondered at this, but at the time it all seemed quite natural); but when the Rabbit actually took a watch out of its waistcoat-pocket, and looked at it, and then hurried on, Alice started to her feet, for it flashed across her mind that she had never before seen a rabbit with either a waistcoat-pocket, or a watch to take out of it, and burning with curiosity, she ran across the field after it, and fortunately was just in time to see it pop down a large rabbit-hole under the hedge.
'''

# Word Cloud を生成する。
wc = WordCloud(background_color='white', max_words=2000,
               mask=mask, contour_width=3, contour_color='steelblue')
wc.generate(text)
wc.to_file('wordcloud.png')