python crawling - 워드 클라우드

BANG·2020년 11월 28일

Crawling

목록 보기
3/3

워드 클라우드 만들기

파일 입출력

f = open("test.txt", "w", encoding="utf-8")
f.write("안녕, 스파르타!\n")

for i in [1, 2, 3, 4, 5]:
    f.write(f"{i}번째 줄이에요\n")

f.close()

with open("test.txt", "r", encoding="utf-8") as f:    # 파일을 열고 알아서 닫아라
    lines = f.readlines()     # 한 줄씩 읽어라
    for line in lines:
        print(line)
text = ''
with open("test.txt", "r", encoding="utf-8") as f:
    lines = f.readlines()
    for line in lines:
        text += line

print(text)

워드 클라우드 만들기

  • 파이참의 file → setting → project interpreter 에서 wordcloud 패키지 다운로드

  • 카카오톡 대화창에서 메뉴 → 대화 내용 → 대화 내보내기


사용 가능한 폰트 목록 확인하기

import matplotlib.font_manager as fm

# 이용 가능한 폰트 중 '고딕'만 선별
for font in fm.fontManager.ttflist:
    if 'Gothic' in font.name:
        print(font.name, font.fname)

워드 클라우드 만들기

from wordcloud import WordCloud

wc = WordCloud(font_path='위에서 확인한 폰트 경로', background_color="white", width=600, height=400)
wc.generate(text)
wc.to_file("result.png")

from wordcloud import WordCloud

text = ''
with open("kakao.txt", "r", encoding="utf-8") as f:
    lines = f.readlines()
    for line in lines:
        text += line

wc = WordCloud(font_path='C:/Windows/Fonts/malgun.ttf', background_color="white", width=600, height=400)
wc.generate(text)
wc.to_file("result.png")

데이터 클렌징

  • 대화내용 중, 시간이랑 닉네임도 포함되 있음
  • 불 필요한 부분을 제거
from wordcloud import WordCloud

text = ''
with open("kakao.txt", "r", encoding="utf-8") as f:
    lines = f.readlines()
    for line in lines[5:]:
        if '] [' in line:    # 시스템 메시지를 제거(입장, 날짜 선 등)
            text += line.split('] ')[2].replace('ㅋ', '').replace('ㅎ', '').replace('ㅇ', '').replace('ㅠ', '').replace('이모티콘\n', '').replace('사진\n', '').replace('삭제된 메시지입니다', '')  # 대화만 나오도록 자르기

# print(text)

wc = WordCloud(font_path='C:/Windows/Fonts/malgun.ttf', background_color="white", width=600, height=400)
wc.generate(text)
wc.to_file("result.png")
  • 원하는 모양으로 만드려면 어떤 모양이든 흰색 배경의 이미지가 있으면 만들 수 있음
  • 모양과 배경이 확연하게 차이나는 이미지가 좋음
  • 이미지를 다운받은 후, 이미지를 스텐실(컴퓨팅에서는 mask라는 표현을 사용)로 사용해서 검은 부분에만 글씨를 채워놓도록 설정.
from wordcloud import WordCloud
from PIL import Image
import numpy as np

text = ''
with open("kakao.txt", "r", encoding="utf-8") as f:
    lines = f.readlines()
    for line in lines[5:]:
        if '] [' in line:    # 시스템 메시지를 제거(입장, 날짜 선 등)
            text += line.split('] ')[2].replace('ㅋ', '').replace('ㅎ', '').replace('ㅇ', '').replace('ㅠ', '').replace('이모티콘\n', '').replace('사진\n', '').replace('삭제된 메시지입니다', '')  # 대화만 나오도록 자르기

# print(text)

mask = np.array(Image.open('cloud.png'))
wc = WordCloud(font_path='C:/Windows/Fonts/malgun.ttf', background_color="white", mask=mask)
wc.generate(text)
wc.to_file("result_masked.png")
profile
Record Everything!!

0개의 댓글