Pythonで英文からワードクラウドを作成する方法

wordcloud_cliというツールを利用してコマンドラインからwordcloudを作成します。

インストール

pipを使ってインストールします。

pip install wordcloud

Anaconda Promptでインストールしました。

実行

実行する時には、英文テキストが入力されているテキストファイルが必要です。lorem ipsumのテキストが入力されているlorem.txtを用意しました。

まずは、一番基本的なワードクラウドを作成します。

wordcloud_cli --text lorem.txt --imagefile wordcloud_b.png

wordcloud

wordcloud_b.pngという画像ファイルが保存されます。

背景の色を指定

wordcloud_cli --background white --text lorem.txt --imagefile wordcloud_w.png

背景はデフォルトでは黒ですが、--background whiteで白にできます。

wordcloud

画像の横・縦指定

wordcloud_cli --width 500 --height 500 --text lorem.txt --imagefile wordcloud_b2.png

widthやheightオプションで大きさを指定できます。

wordcloud

余白指定

wordcloud_cli --margin 15 --text lorem.txt --imagefile wordcloud_b3.png

marginで言葉の周りの余白を調整できます。

wordcloud

単語の最低文字数を指定

wordcloud_cli --min_word_length 5 --text lorem.txt --imagefile wordcloud_b4.png

min_word_lengthでワードクラウドに追加される単語の最低文字数を指定できます。全ての単語が5文字以上になりました。

wordcloud

マスク画像を使用

この画像をmask.pngとして保存しておきます。

mask

以下のように実行すれば、上の画像の通りに単語が配置されます。

wordcloud_cli --mask mask.png --text lorem.txt --imagefile wordcloud_b5.png

wordcloud