with open("test.txt", "w", encoding="utf-8") as f:
f.write("각 줄마다 번호를 적은 파일입니다.\n")
for i in [1,2,3,4,5]:
f.write(f"이것은 {i}번째 줄입니다.\n")
텍스트파일 읽기with open("test.txt", "r", encoding="utf-8") as f:
lines = f.readlines()
for line in lines:
print(line)
패키지 설치
wordcloud
라는 패키지를 이용하여 워드 클라우드를 만들어보도록 하겠습니다. Settings/Preferences > Project Interpreter에서 설치해주세요.
PC 카톡에서 채팅방을 연 후 메뉴 > 대화 내용 > 대화내보내기 해서 대화 내용을 텍스트 파일로 저장한 후 프로젝트 폴더로 옮겨주세요.
3) 카카오톡 텍스트 파일 읽기text = ""
# 파일 이름은 맞게 바꿔주세요!
with open("kakaotalk.txt", "r", encoding="utf-8") as f:
lines = f.readlines()
for line in lines:
text+=line
print(text)
4) 한글 폰트 찾기#폰트 검색
import matplotlib.font_manager as fm
# 이용 가능한 폰트 중 '고딕'만 선별
for font in fm.fontManager.ttflist:
if 'Gothic' in font.name:
print(font.name, font.fname)
font_path = 'C:/Windows/Fonts/malgunbd.ttf'
5) 워드클라우드 만들기
from wordcloud import WordCloud
#뒤에 font_path자리에 위에서 찾은 경로('C:/Windows/Fonts/malgunbd.ttf')를 넣어줌
wc = WordCloud(font_path=font_path, background_color="white", width=600, height=400)
wc.generate(text)
wc.to_file("result.png")
6) 데이터클렌징
from wordcloud import WordCloud
text = ""
# 파일 이름은 맞게 바꿔주세요!
with open("kakaotalk.txt", "r", encoding="utf-8") as file:
lines = file.readlines()
for line in lines:
if '] [' in line:
text += line.split('] ')[2].replace('ㅋ','').replace('ㅠ','').replace('ㅜ','').replace('사진\n','').replace('이모티콘\n','').replace('삭제된 메시지입니다','')
font_path = 'C:/Windows/Fonts/CoreGTM3.otf'
wc = WordCloud(font_path=font_path, background_color="white", width=600, height=400)
wc.generate(text)
wc.to_file("result.png")
7) 워드 클라우드
from PIL import Image
import numpy as np
mask = np.array(Image.open('cloud.png'))
wc = WordCloud(font_path=font_path, background_color="white", mask=mask)
wc.generate(text)
wc.to_file("result_masked.png")
완성
from wordcloud import WordCloud
from PIL import Image
import numpy as np
text = ''
with open("KakaoTalk.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('삭제된 메시지입니다','').replace('샵검색','').replace('받기 완료','').replace('내가','').replace('난','').replace('오늘','').replace('너','').replace('동영상','').replace('나는','').replace('나도','')
mask = np.array(Image.open('cloud.png'))
wc = WordCloud(font_path='C:/Windows/Fonts/Hancom Gothic Bold.ttf', background_color="white", mask=mask)
wc.generate(text)
wc.to_file("result_masked.png")