[wordcloud] naver cafe_게시판 글 목록
2021. 5. 20. 01:27ㆍPython/코딩
Ver. Jupyter Notebook (Anaconda3)
▶ naver cafe_게시판 글 목록
수집: 글 작성 상위 작성자(pie chart), 글 제목 (wordcloud), 좋아요
코딩: github
JeongJaeyoung0/text_analysis
텍스트 감성분석. Contribute to JeongJaeyoung0/text_analysis development by creating an account on GitHub.
github.com
2021.05.20
# wordcloud_naver cafe_게시글 목록
step 1. 글 작성 상위 20 작성자 pie chart
step 2. 글 제목 wordcloud
pwd
### step 0. 준비
import scipy as sp
import pandas as pd
import numpy as np
import re
import collections
# konlpy 한글 텍스트 분석 패키지
from konlpy.tag import Kkma ; kkma = Kkma()
from konlpy.tag import Hannanum ; hannanum = Hannanum()
from konlpy.tag import Okt ; t = Okt()
from konlpy.tag import *
import pickle # 모델 파일 저장
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import Pipeline
from sklearn.metrics import accuracy_score
from sklearn.model_selection import train_test_split
# 그래프
%matplotlib inline
import os
import matplotlib.pyplot as plt
import seaborn as sns
import graphviz
from sklearn.tree import export_graphviz
# 그래프 문자 깨지는 것 대처
import matplotlib
from matplotlib import font_manager, rc
import platform
if platform.system() == 'Windows':
# 윈도우인 경우
font_name = font_manager.FontProperties(fname="c:/Windows/Fonts/malgun.ttf").get_name()
rc('font', family=font_name)
else:
# Mac 인 경우
rc('font', family='AppleGothic')
# 워닝 없애주는 것
import warnings
warnings.filterwarnings('ignore')
### step 1. 전처리
df = pd.read_excel(r'G:\내 드라이브\00_python\00_data\crawler_naver cafe_☰ 통합 Q & A ☰_게시판 글.xlsx')
print(len(df))
df
### step 2. matplot
name = (df['작성자'].value_counts())
name
name_list = name.head(20)
name_list
name_list.keys()
df_name.index
df_name.values
df_name['작성자']
# pie chart
fig = plt.figure(figsize=(8,8)) # 캔버스 생성
fig.set_facecolor('white') # 캔버스 배경색을 하얀색으로 설정
ax = fig.add_subplot() # 프레임 생성
pie = ax.pie(name_list,
labels=name_list.keys(),
autopct=lambda p : '{:.2f}%'.format(p))
plt.savefig('pie chart.png')
plt.show()
### step 3. wordcloud
text_sum = ''
# 한 문장으로 합치기
for i in df['제목']:
text_sum = text_sum + i
text_sum
# 자음, 모음, 알파벳, 특수기호, 특수기호 제거
text_sub = re.compile('[|ㄱ-ㅎ|ㅏ-ㅣ|?!.,\^<>]+').sub('',text_sum)
text_sub
tokens_ko = t.morphs(text_sub)
tokens_ko
import nltk
from konlpy.tag import Okt; t = Okt
ko = nltk.Text(tokens_ko)
print(len(ko.tokens)) # 토큰 전체 갯수
print(len(set(ko.tokens))) # 토큰 unique 갯수
# 불용어 : 인터넷 검색 시 검색 용어로 사용하지 않는 단어. 관사, 전치사, 조사, 접속사 등 검색 색인 단어로 의미가 없는 단어
stop_words = ['.','가',"!",'\r\n\r\n','\r\n','\n','\n ','요','답변','...','을','수','에','질문','제','를','이','도',
'좋','1','는','로','으로','2','것','은','다',',','니다','대','들',
'2017','들','데','..','의','때','겠','고','게','네요','한','일','할',
'10','?','하는','06','주','려고','인데','거','좀','는데','~','ㅎㅎ',
'하나','이상','20','뭐','까','있는','잘','습니다','다면','했','주려',
'지','있','못','후','중','줄','6','과','어떤','기본','!!',
'단어','라고','중요한','합','가요','....','보이','네','무지',
'ㅋㅋ', 'ㅋㅋㅋ', 'ㅋ', '만', '아', '안,' '나', '사진', '난', '이모티콘',
'내', '그', '근데', '더', '안', '나', '임', '저', '면', '듯', '년', '하면', '에서',
'너', '서', '랑', '에서', '니깐', '적', '하고', '??', '~~', '~~~', '[', ']', '시',
'관련', '드립니다', '(', ')', '분', '하', '압니다', '혹시']
tokens_ko = [each_word for each_word in tokens_ko
if each_word not in stop_words]
ko = nltk.Text(tokens_ko)
data = ko.vocab().most_common(300)
data
from wordcloud import WordCloud, STOPWORDS
from PIL import Image
mask = np.array(Image.open('t.png'))
plt.imshow(mask)
wc = WordCloud(font_path='c:/Windows/Fonts/malgun.ttf',
background_color="white",
#stopwords = stopwords,
max_words=2000,
mask=mask,
max_font_size=300).generate_from_frequencies(dict(data))
plt.figure(figsize=(30,15))
#wc.words_
plt.imshow(wc)
# 다음과 같이 파일로 저장
wordcloud.to_file('wordcloud.png')
'Python > 코딩' 카테고리의 다른 글
[python] crawler_google image(colab) (0) | 2021.07.08 |
---|---|
[python] 소수 판별 (에라토스테네스의 체) (0) | 2021.06.03 |
[crawler] naver cafe_게시판 글 목록 (0) | 2021.05.19 |
[python] crawler_google image (0) | 2021.05.18 |
[crawler] youtube(selenium) (1) | 2021.05.17 |