1
1

More than 1 year has passed since last update.

python初心者はWordCloudで遊んでみたい3

Last updated at Posted at 2021-09-20

前回まで

前回はjanomeを使って色々やって遊んでた。やっぱり楽しい。
今回はWordCloudを使って多く使われている文字を可視化していく。 

環境

Google Colaboratory
※WordCloudでGoogle Colabでやる場合、pipでインストールせずそのままできます。

とりあえずやってみる

※sample.txtには、赤ずきんの英語版が書き込んであります。

from wordcloud import WordCloud

f = open("sample.txt", "r", encoding="UTF-8")
text = f.read()

#オブジェクトを作成
wordcloud = WordCloud()
#(文字列)からwordcloudを作成
wordcloud.generate(text)
#画像を作成
wordcloud.to_file('wc1.png')

実行結果

wc1.png
しっかり、Redやgrandmathierなどが大きく表示されています。

※作成した画像はcontentの下に保存されています。
スクリーンショット 2021-09-21 0.58.19.png

書式をいじくってみる

画像サイズや背景、文字の色などを変更することができます。

from wordcloud import WordCloud

f = open("sample.txt", "r", encoding="UTF-8")
text = f.read()

wordcloud = WordCloud(background_color="white",
               colormap="summer",
               collocations=False)

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

実行結果

wc2.png
background_color : 背景色
colormap : 文字の色
collocations : 連語を分割して一つの単語にする

他にも、使用する単語の最大数、不要な単語を表示しない、表示する文字数を制限、などがある。
上記のやつ以外も割とあるがどれも使わなそう...

まとめ

今回は、WordCloudを軽く触ってみた。物語だと出るだろうなって文字が出てくるが歌詞など、Twitterのツイートなどだとイメージが湧かないからとても面白そう。
次回は、一番つまずくと書かれていた日本語化をやっていく。

1
1
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
1
1