Pythonデータ分析-3週目

12190 ワード

Wordクラウドの作成


入庫する

conda install -c conda-forge wordcloud

import numpy as np
from PIL import Image
from wordcloud import WordCloud
import matplotlib.pyplot as plt

データの読み込み

result = ""

for number in range(1,15):
    index = '{:02d}'.format(number)
    filename = "Sequence_" +index + ".txt"
    print(filename)
    text = open("./data/"+filename, 'r', encoding='utf-8-sig')
    result += text.read().replace("\n", " ")
import re
pattern = '[^\w\s]' # 특수 기호 제거
text = re.sub(pattern=pattern, repl='', string=result)
text

ワードクラウドの作成

import matplotlib.font_manager as fm

# 이용 가능한 폰트 중 '고딕'만 선별
for f in fm.fontManager.ttflist:
    if 'Gothic' in f.name:
        print(f.fname)
font_path = '/System/Library/Fonts/Supplemental/AppleGothic.ttf'

wc = WordCloud(font_path=font_path, background_color="white")
wc.generate(text)

****plt.figure(figsize=(50,50))
plt.axis("off")
plt.imshow(wc)
plt.show()

テキストクラウドの外観を描画する

# Generate a word cloud image
mask = np.array(Image.open('./data/sparta.png'))
wc = WordCloud(font_path=font_path, background_color="white", mask=mask)
wc.generate(text)

f = plt.figure(figsize=(50,50))
f.add_subplot(1,2, 1)
plt.imshow(mask, cmap=plt.cm.gray)
plt.title('Original Stencil', size=40)
plt.axis("off")
f.add_subplot(1,2, 2)
plt.imshow(wc, interpolation='bilinear')
plt.title('Sparta Cloud', size=40)
plt.axis("off")
plt.show()

テキストクラウドイメージの保存

mask = np.array(Image.open('./data/sparta.png'))
wc = WordCloud(font_path='/System/Library/Fonts/Supplemental/AppleGothic.ttf', background_color="white", mask=mask)
wc.generate(text)

f = plt.figure(figsize=(50,50))
plt.imshow(wc, interpolation='bilinear')
plt.title('Twitter Generated Cloud', size=40)
plt.axis("off")
plt.show()
f.savefig('./wordcloud_ex1.png')