공부👻

카카오톡 크롤링 - 워드 클라우드, 파이썬 🥳~

당근먹는하니 2022. 12. 29. 16:11
728x90
반응형

IDE가 뭔지부터 알아내야 했다. 

그 후 파이참을 깔았다. 또 pip도 터미널에서 sudo로 설치했고, pip을 통해 워드 클라우드도 설치했다. 

디버깅 하는 법도 검색했다. 처음엔 파일을 같은 곳에 넣는 것도 못했다. 

 

문제는 데이터 클렌징~

 

일단 내가 검색해서 나온 결과들이랑 대화내용 내보내기 한 내용이랑은 달랐다...

그래서 처음엔 그냥 복사 붙여넣기해서 왜 text가 안 나오지?!!했는데 정말 데이터가 달라서 안 나오는 것이었다. (우엉이 대박)

 

웅과 식널한테 도움 요청을 했었다. 

 

이건 안됐다.

예외있는, 여기선 line.split(', ')했을때 [1]이 없는 애들이라거나... 때문에 계속 오류가 발생했던 거여서 if를 붙여줬다. 

&& 이랑 & 으로 하니까 안되길래...ㅎㅎ 

 

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

import matplotlib.font_manager as fm

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

text = ''
with open("kakao_your.txt", "r", encoding="utf-8") as f:
    lines = f.readlines()
    for line in lines[5:]:
        if ', ' in line:
            if ' : ' in line:
                text += line.split(', ')[1].split(' : ')[1].replace('ㅋ','').replace('ㅠ','').replace('ㅜ','').replace('사진','').replace('동영상','').replace('샵검색','').replace('이모티콘\n','').replace('앜','').replace('나는','').replace('근데','').replace('삭제된 메시지입니다','')
            # print(line.split(', ')[1].split(' : ')[1])
            # text += line.split(', ')[1]
    print(text)

    font_path = 'C:/System/Library/Fonts/Supplemental/AppleGothic.ttf'

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

replace말고 외부 라이브러리?를 이용해서 하시던데 일단 겁내서 안 했다. 

ㅠㅠㅠ감동 드디어 해보는구나 이걸

 

없애보고 싶은 단어가 너무 많아서 라이브러리를 사용했다. 

 

 

from wordcloud import WordCloud,STOPWORDS
from PIL import Image
import numpy as np
import matplotlib.font_manager as fm

# 이용 가능한 폰트 중 '고딕'만 선별
for font in fm.fontManager.ttflist:
    if 'Gothic' in font.name:
        print(font.name, font.fname)
stopwords = set(STOPWORDS)
stopwords.add("헐")
stopwords.add("너무")
stopwords.add("나")
stopwords.add("진짜")
stopwords.add("뭔가")




text = ''
with open("kakao_your.txt", "r", encoding="utf-8") as f:
    lines = f.readlines()
    for line in lines[5:]:
        if ', ' in line:
            if ' : ' in line:
                text += line.split(', ')[1].split(' : ')[1].replace('ㅋ','').replace('ㅠ','').replace('ㅜ','').replace('사진','').replace('동영상','').replace('샵검색','').replace('이모티콘\n','').replace('앜','').replace('나는','').replace('근데','').replace('삭제된 메시지입니다','')
            # print(line.split(', ')[1].split(' : ')[1])
            # text += line.split(', ')[1]
    print(text)

    font_path = 'C:/System/Library/Fonts/Supplemental/AppleGothic.ttf'

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

 

728x90
반응형