Word Cloud

Word Cloudインストール


pip3 install wordcloud

matplotlibインストール

Word Cloudはmatplotlibに依存しています


pip3 install matplotlib

from wordcloud import WordCloud

text = "When someone you care about is grieving, it's hard to find the right words.\
	What should you say in a condolence message? What common sympathy expressions should you avoid? What else can you do to comfort a bereaved friend?\
	ven those with the best intentions might say something inappropriate to the bereaved.\
	Hurtful sentiments can damage relationships; so many individuals stay away, fearing they'll say the wrong thing.\
	So what can you do? Stick to the basics when speaking with the bereaved.\
	Communicate in some way your sadness at their loss and if you have some knowledge of the deceased,\
	mention a quality you admired. For example: I was so sad to hear of Jill's death. Her wonderful nature always gave me a lift."\

bg_color = "white" #背景色
path = "/usr/share/fonts/ipa-gothic/ipag.ttf" #フォントファイルの場所
width = 800
height = 600

wordcloud = WordCloud(
        background_color = bg_color,
        font_path = path,
        width = width,height = height).generate(text)

wordcloud.to_file("./wordcloud_sample.png") #保存先
 

結果

リスト化された文字列に対してWord Cloudを使用する

Word Cloudの引数である文章は半角スペースで区切る必要があるので、join関数を使用します

from wordcloud import WordCloud

word_list = ["aaa","tttt","teee","aaa"]

text = ' '.join(word_list) #半角スペースごとに区切る

bg_color = "white"
path = "/usr/share/fonts/ipa-gothic/ipag.ttf"
width = 800
height = 600

wordcloud = WordCloud(
        background_color = bg_color,
        font_path = path,
        width = width,height = height).generate(text)

wordcloud.to_file("./wordcloud_sample.png")



参考

Word Cloud

Posted by iser