26
27

More than 5 years have passed since last update.

Pythonでテキストマイニング

Last updated at Posted at 2018-04-16

背景

ただなんとなくやってみようと…。

環境

  • Windows
  • Python 2.7

使用ライブラリ

  • janome:他にもmecabなどがありますが、今回はこちら
  • matplotlib:描画用
  • wordcloud:描画用

これらをpip installでインストールします。

janome確認

このライブラリがどのように動くかを確認します。

from janome.tokenizer import Tokenizer

t = Tokenizer()
tokens = t.tokenize(u'私はPythonが好きです。')
for token in tokens:
    print str(token).decode('utf-8')

※Windowsのコマンドプロンプトだと文字コードに注意してください。

実行結果は下記です。

私      名詞,代名詞,一般,*,*,*,私,ワタシ,ワタシ
は      助詞,係助詞,*,*,*,*,は,ハ,ワ
Python  名詞,固有名詞,組織,*,*,*,Python,*,*
が      助詞,格助詞,一般,*,*,*,が,ガ,ガ
好き    名詞,形容動詞語幹,*,*,*,*,好き,スキ,スキ
です    助動詞,*,*,*,特殊・デス,基本形,です,デス,デス
。      記号,句点,*,*,*,*,。,。,。

データ

実際テキストマイニングするデータですが、
当初Twitterのデータを取得する方法も考えたが途中頓挫したので、国会の議事録を取得
http://www.shugiin.go.jp/internet/itdb_kaigiroku.nsf/html/kaigiroku/kaigi_l.htm

実装

まず上のデータをちょっと加工してテキストで保存。

from janome.tokenizer import Tokenizer

# データ読み込み
fin = open('test_data.txt')
txt = fin.read().replace('\n', '')
fin.close()

# テキストマイニング実行
t = Tokenizer()
tokens = t.tokenize(txt.decode('utf-8'))
words = {}
for token in tokens:
    data = str(token).decode('utf-8').split()[1].split(',')
    # 名詞のみ取得
    if data[0] == u'名詞':
        key = data[6]
        if key not in words:
            words[key] = 1
        else:
            words[key] += 1

ソースが汚いのはおいといて、
これでWindowsで実行すると、[文字:個数]の辞書型が取得できます。

描画

wordcloudを使って描画してみます、一般的な使い方はこちらです。

wordcloud = WordCloud().generate(txt)

テキストのままだとgenerateもしくはgenerate_from_txt、辞書型の場合はgenerate_from_frequenciesになります。
では上のwordsで描画してみます。

失敗

import matplotlib.pyplot as plt
from wordcloud import WordCloud

wordcloud = WordCloud().generate_from_frequencies(words)
plt.figure(figsize=())
plt.imshow(wordcloud)
plt.axis("off")
plt.show()

Figure_1.png

幾何学模様の完成です(笑)

成功

先程失敗した原因はフォントの指定がないためでした。

import matplotlib.pyplot as plt
from wordcloud import WordCloud

# Windows標準フォントを定義
fpath = "C:\\Windows\\Fonts\\msgothic.ttc"
wordcloud = WordCloud().generate_from_frequencies(words)
plt.figure(figsize=())
plt.imshow(wordcloud)
plt.axis("off")
plt.show()

Figure_1-1.png

見事に成功。

※画像が見にくい場合はWordCloudの引数に背景色の設定などがありますので、適宜変更するとよいと思います。

26
27
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
26
27