LoginSignup
26
12

More than 5 years have passed since last update.

Word Cloudで同じ単語が2回出てきて困る

Last updated at Posted at 2019-02-21

結論

collocationsオプションを書かないと、複数の単語をまとめて1語として書き出すので、同じ単語が複数回出ているように見えることがあります。

Word Cloudで単語が重複する

Andreas Mueller氏のWorldCloudライブラリ https://github.com/amueller/word_cloud を使ってみたけれど、同じ単語が2回ぐらい出てきてしまって困った、という話です。

badpoint.png
真ん中に大きく「仕事」が出てるのですが下の端にも「仕事」が出ています。困る。

ちなみにこれは「会社へのご意見」という闇のアンケートをWordCloudで可視化しようとしてみた闇の画像です。
もっと楽しいデータで勉強すればよかった・・・。

実は重複ではない

結論から言うと下の方の「仕事」は「仕事」ではなく「仕事 内容」でした。
このように複数の単語をまとめて1語とされないように、collocationsオプションを書いてあげます。

wordcloud.py
import codecs
from wordcloud import WordCloud

#分かち書きしたテキストの読み込み
text_file = codecs.open('C:/Users/hogehoge/wakachigaki_iken.txt','r','utf-8')
text = text_file.read()
text_file.close()

# 画像に出したくない単語リスト(本当はもっと色々)
stop_words = [u'なる', u'ある', u'いる', u'する', u'ない', u'れる', u'ため', u'こと', u'もの']

wordcloud = WordCloud(background_color="white",
    font_path = "C:/Windows/Fonts/meiryo.ttc",
    stopwords = set(stop_words),
    collocations = False, # 複合語のオプションをオフ
    width = 800,
    height = 600).generate(text)

wordcloud.to_file("C:/Users/hogehoge/iken.png")

print('End')

これで消えたはずです。
badpoint2.png
ただし「住宅 手当」なんていう単語も消えて「住宅」「手当」になってしまいました。
「住宅手当」として拾いたいのであれば、分かち書きの時点で「住宅手当」は一語だと認識させておかないとダメですね。

Githubのissueを見れば即解決なのですが、自分のように英語が読めない人の参考になればと思って書いてみました。

(蛇足メモ)分かち書き

分かち書きファイルはこんな感じで作りました。
テキストファイルは事前にutf-8にしてあります。

wakachi.py
import codecs
text_file = codecs.open('C:/Users/hogehoge/iken.txt','r','utf-8')
txt = text_file.read()

# テキストを改行で区切った配列にする
sentences = txt.split('\n')

# janomeでテキスト分解
from janome.tokenizer import Tokenizer
t = Tokenizer()

write_file = codecs.open('C:/Users/hogehoge/wakachigaki_iken.txt','w','utf-8')

for sentence in sentences:
    tokens = t.tokenize(sentence)

    # 出てきた単語から名詞・動詞・形容詞・形容動詞だけ抽出
    for token in tokens:
        if token.part_of_speech.split(',')[0] in['名詞', '動詞', '形容詞', '形容動詞']:
            write_file.write(token.base_form + ' ')

    write_file.write('\n')

write_file.close()
text_file.close()

print('End')
26
12
1

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
12