본문 바로가기
Python

[Python] 워드클라우드 만들기

by Couldi 2021. 9. 12.
반응형

단톡방 내용으로 만든 워드클라우드 되시겠다.

사용한 패키지

wordcloud
PIL
numpy

완성 코드

from wordcloud import WordCloud
from PIL import Image
import numpy as np

text = ""

with open("talk.txt", "r", encoding="utf-8") as f:
    lines = f.readlines()
    for line in lines:
        if '] [' in line:
        # 요부분은 사실상 데이터클랜징 하는 부분. 지우고 싶은 단어들에 맞춰서 수정하면 된다.
            text += line.split('] ')[2].replace('ㅋ', '').replace('ㅠ', '').replace('ㅜ', '').replace('사진\n', '').replace('이모티콘\n', '').replace('삭제된 메시지입니다', '').replace('https', '').replace('bit', '').replace('ly', '').replace('blog', '').replace('naver', '')

font_path = 'C:/Windows/Fonts/NanumGothicBold.ttf'

wc = WordCloud(font_path=font_path, background_color="white", width=600, height=400)
wc.generate(text)
wc.to_file("result.png")

mask = np.array(Image.open('img.png'))
wc = WordCloud(font_path=font_path, background_color="white", mask=mask)
wc.generate(text)
wc.to_file("result_masked.png")

후기

간단하게 할 수 있는 작업들이라 생각보다 재밌게 한 듯. 밀키트로 요리한 느낌이다.

참고자료

-

반응형

댓글