Welcome

カキノタblog

自分の興味あるテーマを中心に、図解多めに記事を作成していきたいと思います。

Python テキストをファイルからロードする

from wordcloud import WordCloud

with open('LICENSE.txt') as f:
	text = f.read()
	
wc = WordCloud().generate(text)
wc.generate(text)
wc.to_file('LICENSE.png')

python.exeがあるディレクトリ内のLICENSE.txtを読み込んでワードクラウドにしてみました。

画像:テキストをファイルからロードする 

▼日本語のファイルを読み込む。

from wordcloud import WordCloud

FONT_FILE = "C:\Windows\Fonts\MSGOTHIC.TTC"

with open('hashire_merosu.txt', encoding='utf-8') as f:
	text = f.read()
	
wc = WordCloud(width=640, height=480, background_color='white',font_path=FONT_FILE).generate(text)
wc.generate(text)
wc.to_file('merosu.png')

青空文庫からダウンロードしたファイルをutf-8に変換し直したファイルをワードクラウド化。

画像:テキストをファイルからロードする2 

形態素解析(単語に分解)していないので「メロスは」「まだ陽は沈まぬ」みたいになっています。