Python
카카오톡 대화내용으로 워드 클라우드 만들기
˙ᵕ˙
2020. 10. 3. 16:37
파일 쓰기
f = open("test.txt", "w", encoding="utf-8")
f.write("파일 쓰기 테스트\n")
f.write("파일 쓰기 테스트\n")
f.write("파일 쓰기 테스트\n")
f.close()
- 실행
파일 읽기
text = ''
with open("test.txt", "r", encoding="utf-8") as f:
lines = f.readlines()
for line in lines:
text += line
print(text)
워드클라우드
- 워드클라우드 패키지 다운로드
- 워드클라우드 사용 전 폰트 선택을 해야함
import matplotlib.font_manager as fm
# 이용 가능한 폰트 중 '고딕'만 선별
for font in fm.fontManager.ttflist:
if 'Gothic' in font.name:
print(font.name, font.fname)
- 원하는 폰트 위치 검색
- 워드클라우드 만들기
- font_path에 검색해 놓은 폰트 위치를 붙여넣기 ( 경로의 역슬래시(\)를 슬래시(/)로 바꿔야 정상작동 )
from wordcloud import WordCloud
wc = WordCloud(font_path=font_path, background_color="white", width=600, height=400)
wc.generate(text)
wc.to_file("result.png")
- 텍스트 파일을 읽고 워드 클라우드 만들기
from wordcloud import WordCloud
text = ''
with open("test.txt", "r", encoding="utf-8") as f:
lines = f.readlines()
for line in lines:
text += line
print(text)
wc = WordCloud(font_path='C:/WINDOWS/Fonts/AdobeGothicStd-Bold.otf', background_color="white", width=600, height=400)
wc.generate(text)
wc.to_file("result.png")
- 결과
카카오톡 대화내용 가져오기
- 대화방에서 메뉴 -> 대화내용 -> 대화 내보내기
- 원하는 데이터만 가져오기
- 카카오톡 대화내용을 저장하면 [이름] [시간] [대화내용] 의 형태로 저장이 되는데 대화내용만 사용할 예정이기 때문에 전처리 과정이 필요하다.
- replace함수를 통해서 필요없는 내용들, 시스템메시지, 결과에서 제거 할 내용 등 을 제거한다
from wordcloud import WordCloud
text = ''
with open("kakao.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('삭제된 메시지입니다', '')
print(text)
wc = WordCloud(font_path='C:/WINDOWS/Fonts/AdobeGothicStd-Bold.otf', background_color="white", width=600, height=400)
wc.generate(text)
wc.to_file("result.png")
- 결과
원하는 모양으로 워드클라우드 만들기
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:
if '] [' in line:
text += line.split('] ')[2].replace('ㅋ', '').replace('ㅠ', '').replace('ㅜ', '').replace('사진\n', '').replace(
'이모티콘\n', '').replace('삭제된 메시지입니다', '')
mask = np.array(Image.open('cloud.png'))
wc = WordCloud(font_path='C:/WINDOWS/Fonts/AdobeGothicStd-Bold.otf', background_color="white", mask=mask)
wc.generate(text)
wc.to_file("result_masked.png")
- 결과