💻프로그래밍/👩‍🔬빅데이터분석

[파이썬] 한글제목의 키워드 분석하기(+워드클라우드)📰

hyerimmy 2021. 2. 17. 23:22

2021.02.17
PM 22:00 - 23:15

import json
import re
from konlpy.tag import Okt
from collections import Counter
import matplotlib
import matplotlib.pyplot as plt
from matplotlib import font_manager, rc
from wordcloud import WordCloud
inputFileName = '8-2_data\\etnews.kr_facebook_2016-01-01_2018-08-01_4차 산업혁명'
data = json.loads(open(inputFileName+'.json','r',encoding='utf-8').read()) #json : json파일 다루기 위한 모듈
data #출력하여 내용 확인
message = ''
for item in data:
    if 'message' in item.keys():
        message = message + re.sub(r'[^\w]', '', item['message']) +'' #문자나 숫자가 아닌 것은 공백으로 치환
message #출력하여 내용 확인
nlp = Okt() #품사 태깅 패키지 Okt
message_N = nlp.nouns(message) #명사만 추출해 message_N에 저장
message_N #출력하여내용확인
count = Counter(message_N) #단어별 출현 횟수 계산
count
word_count = dict()
for tag, counts in count.most_common(80): #출현횟수가 많은 상위 80개 단어
    if(len(str(tag))>1): #길이가 1보다 큰 것만
        word_count[tag] = counts #word_count 딕셔너리에 저장
        print("%s : %d" % (tag, counts)) #출력하면서 확인
#시각적탐색1 : 히스토그램 그리기

##글꼴설정
font_path = "C:\\Users\\LG\\AppData\\Local\\Microsoft\\Windows\Fonts\\NanumSquareB.ttf"
font_name = font_manager.FontProperties(fname = font_path).get_name()
matplotlib.rc('font',family=font_name)

##그래프그리기
plt.figure(figsize = (12,5))
plt.xlabel('키워드')
plt.ylabel('빈도수')
plt.grid(True)
sorted_Keys = sorted(word_count, key = word_count.get, reverse = True)
sorted_Values = sorted(word_count.values(), reverse=True)
plt.bar(range(len(word_count)), sorted_Values, align='center')
plt.xticks(range(len(word_count)), list(sorted_Keys), rotation='75')
plt.show()
#시각적탐색2 : 워드클라우드 그리기

## 워드클라우드 나타내기
wc = WordCloud(font_path, background_color = 'ivory', width=800, height=600) #워드클라우드객체생성
cloud = wc.generate_from_frequencies(word_count) #word_count의 cloud를 객체에 저장
plt.figure(figsize = (8,8))
plt.imshow(cloud)
plt.axis('off')
plt.show()

## 이미지로 저장
cloud.to_file(inputFileName + '_cloud.jpg')

최종출력결과