Python 데이터분석 - 3주차

김영민·2021년 11월 1일
0

워드클라우드 만들기

라이브러리 불러오기

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')
profile
“Stay hungry, Stay foolish.”

0개의 댓글

관련 채용 정보