250x250
Link
나의 GitHub Contribution 그래프
Loading data ...
Notice
Recent Posts
Recent Comments
관리 메뉴

Data Science LAB

[Python] 데이터 에듀 ADP 실기 모의고사 1회 3번 파이썬 ver. (비정형 텍스트마이닝) 본문

adp 실기/기출문제

[Python] 데이터 에듀 ADP 실기 모의고사 1회 3번 파이썬 ver. (비정형 텍스트마이닝)

ㅅ ㅜ ㅔ ㅇ 2022. 8. 31. 13:59
728x90

사용 데이터 : 영화 기생충_review.txt, 영화 기생충_사전.txt

'영화 기생충_review.txt'는 다음 영화 사이트의 영화 '기생충'에 대한 review 데이터이며, '영화 기생충_사전.txt'은 영화 기생충의 출연진의 이름과 극중 이름, 감독 이름이 있는 데이터이다.

 

1. '영화 기생충_review.txt' 데이터를 읽어온 뒤 숫자, 특수 문자 등을 제거하는 전처리 작업을 시행하시오. 그리고 '영화 기생충_review.txt'을 사전에 등록하시오.

import pandas as pd

f = open('../data/영화 기생충_review.txt','r')
review = f.read()
review = pd.Series(review.split('\n'))
review

 

데이터를 불러온뒤, \n 을 구분자로 설정해 데이터를 구분하여 시리즈 형태로 변환해줌

 

 

import re
import konlpy

review = review.map(lambda x: re.sub(r'\d', " ", x))
review = review.map(lambda x: re.sub('[-=+,#/\?:^$.@*\"※~&%ㆍ!』\\‘|\(\)\[\]\<\>`\'…》;]', ' ', x))
review

 

정규식을 이용하여 리뷰의 특수문자 제거

 

dicts = pd.read_csv('../data/영화 기생충_사전.txt', sep='\t', encoding='cp949', names=['word'])
dicts

사전 데이터 불러옴

 

 

dicts['pos'] = 'NNP'
dicts.to_csv('./bugs.txt', index=False, header=False)

 

품사를 고유명사(NNP)로 사전 완성후 csv형태로 저장

 

 

from konlpy.tag import Komoran
komoran = Komoran(userdic='bugs.txt')

 

한국어 형태소 분석기인 Komoran을 불러온 뒤, 사용자 사전을 등록함

 

 

2. 영화 기생충_사전.txt를 단어사전으로 하는 TDM을 구축하고 빈도를 파악하고 시각화하시오.

from sklearn.feature_extraction.text import CountVectorizer
cv = CountVectorizer()

cv.fit(dicts['word'])

 

CounterVector함수를 이용하여 dict를 학습시킴

 

 

cv_matrix = cv.transform(review)

name = cv.get_feature_names()
cv_mat = cv_matrix.toarray()
tdm = pd.DataFrame(cv_mat, columns=name)
tdm

 

사전에 저장된 17개 단어의 tdm을 구축

 

 

# 빈도계산
tdm_freq = tdm.sum(axis=0).sort_values(ascending=False)
tdm_freq

 

빈도수 계산 결과, 봉준호, 송강호 ... 순으로 많이 언급된 것을 알 수 있다. 

 

import matplotlib.pyplot as plt
from matplotlib import font_manager, rc
import platform
font_path = 'C:/Windows/Fonts/NGULIM.TTF'
font = font_manager.FontProperties(fname = font_path).get_name()
rc('font', family = font)

tdm_freq.plot(kind='bar', figsize=(10,5))
plt.show()

 

많이 언급된 순으로 막대그래프 시각화 진행

 

 

3. extranoun으로 명사를 추출하여 워드클라우드를 그리고 특성을 파악하시오.

nouns = komoran.nouns(' '.join(review))

from collections import Counter
cnt = Counter(nouns)
temp_df = pd.DataFrame(columns=['명사', '빈도'])
freq = cnt.most_common(10)
tmp_list = []
tmp_list2 = []

for i in freq:
    tmp_list.append(i[0])
    tmp_list2.append(i[1])
    
temp_df['명사'] = tmp_list
temp_df['빈도'] = tmp_list2
temp_df

 

Counter 함수를 이용해 명사의 수를 센 뒤, 내림차순으로 정렬

 

 

words = {}
for i in cnt.most_common(20):
    words[i[0]] = i[1]
    
from wordcloud import WordCloud
import nltk
from nltk.corpus import stopwords

wordcloud = WordCloud(font_path = font_path, background_color='white', colormap='Accent_r',
                      width=1500, height=1000).generate_from_frequencies(words)

plt.imshow(wordcloud)
plt.axis('off')
plt.show()

상위 20개 단어를 추출하여 워드클라우드 생성

 

봉준호 감독과 영화에 대해 많이 언급된 것을 알 수 있다. 

728x90
Comments