설치 목록 (파이썬 버전에 따라 설치가 다르다)
import nltk
import wordcloud
# nltk의 download 메소드 (학습용 데이터셋)
nltk.download()
# 꼬꼬마 모듈
from konlpy.tag import Kkma
kkma = Kkma()
# 문장 분석 : 마침표가 없어도 구분
kkma.sentences('한국어 분석을 해보겠습니다. 과연 잘 나올지 두근두근')
# 명사 분석
kkma.nouns('한국어 분석을 해보겠습니다. 과연 잘 나올지 두근두근')
# 형태소 분석 : 형태소(최소한의 의미 단어)
kkma.pos('한국어 분석을 해보겠습니다. 과연 잘 나올지 두근두근')
# 한나눔 사용
from konlpy.tag import Hannanum
hannanum = Hannanum()
# 명사 분석
hannanum.nouns('한국어 분석을 해보겠습니다. 과연 잘 나올지 두근두근')
# 형태소 분석
hannanum.pos('한국어 분석을 해보겠습니다. 과연 잘 나올지 두근두근')
# 형태소 분석 2 (품사 표시 X)
hannanum.morphs('한국어 분석을 해보겠습니다. 과연 잘 나올지 두근두근')
from konlpy.tag import Okt
# from konlpy.tag import Twitter 구 버전 명령어
# t = Twitter()
t=Okt()
# 명사 분석
t.nouns('한국어 분석을 해보겠습니다. 과연 잘 나올지 두근두근')
# 형태소 분석
t.morphs('한국어 분석을 해보겠습니다. 과연 잘 나올지 두근두근')
# 형태소 분석
t.pos('한국어 분석을 해보겠습니다. 과연 잘 나올지 두근두근')
# WordCloud
# stopwords 불용어 : 분석에 의미가 없는 단어 토큰 -> 제거 필요
from wordcloud import WordCloud, STOPWORDS
import numpy as np
from PIL import Image
# 이미지 관련 모듈 import
# 텍스트 데이터 로드
text = open('DataScience_Ing/data/09. alice.txt').read()
# 이미지 데이터 로드
alice_mask = np.array(Image.open('DataScience_Ing/data/09. alice_mask.png'))
# 불용어 카운트하지 않도록 설정 -> 빈도수에 포함되지 않도록 함
stopwords = set(STOPWORDS)
stopwords.add('said') # said는 분석에 불필요해! 제거!
# 그림그리는 모듈 import
import matplotlib.pyplot as plt
# 현재 사용하는 시스템 환경에 대한 모듈
import platform
# 폰트 경로 설정
path = 'c:/Windows/Fonts/malgun.ttf'
# 폰트 설정 (시스템 환경별로)
from matplotlib import font_manager, rc
if platform.system() == 'Darwin':
rc('font', family = 'AppleGothic')
elif platform.system() == 'Windows':
font_name = font_manager.FontProperties(fname=path).get_name()
rc('font', family = font_name)
else:
print('Unknown System :(')
%matplotlib inline
plt.figure(figsize=(8,8))
plt.imshow(alice_mask, cmap=plt.cm.gray, interpolation='bilinear')
# interpolation='bilinear' -> 보간 : 알려진 지점의 값 사이에 위치한 값을 알려진 값으로부터 추정하는 것
# -> 이미지 깨지지않게 보여줌
plt.axis('off')
plt.show()
# 앨리스에서 어떤 단어가 가장 많이 나왔는지 비율로 표현
wc = WordCloud(background_color='white', max_words=2000, mask=alice_mask,
stopwords=stopwords, collocations=False)
# collocations=False : 연어가 아니라고 설정해줘야 'said Alice가 걸러짐'! (default=True)
wc = wc.generate(text)
wc.words_
# 단어 빈도수 분석결과, 그림으로 표현
plt.figure(figsize=(12,12))
plt.imshow(wc, interpolation='bilinear')
plt.axis('off')
plt.show()
# text
# 텍스트 데이터 로드
text = open('DataScience_Ing/data/09. a_new_hope.txt').read()
# 단어 대치
text = text.replace('HAN', 'Han')
text = text.replace("LUKE'S", 'Luke')
# 이미지 데이터 로드
mask = np.array(Image.open('DataScience_Ing/data/09. stormtrooper_mask.png'))
# 불용어 제거
stopwords = set(STOPWORDS)
stopwords.add('int')
stopwords.add('ext')
wc = WordCloud(max_words=1000, mask=mask, stopwords=stopwords, collocations=False,
margin=10, random_state=1).generate(text)
default_colors = wc.to_array()
# 글자색 바꾸는 함수 생성
import random
def grey_color_func(word, font_size, position, orientation, random_state=None, **kwards):
return 'hsl(0, 0%%, %d%%)' % random.randint(60,100)
# kwargs 정해지지 않은 수의 키워드 파라미터를 받음
plt.figure(figsize=(12,12))
plt.imshow(wc.recolor(color_func=grey_color_func, random_state=3), interpolation='bilinear')
plt.axis('off')
plt.show()
import nltk
from konlpy.corpus import kobill
files_ko = kobill.fileids()
doc_ko = kobill.open('1809890.txt').read()
# konlpy 사이트에서 가져오는 말뭉치
doc_ko
# 말뭉치 분석
from konlpy.tag import Okt
t = Okt()
# 명사 분석
tokens_ko = t.nouns(doc_ko)
tokens_ko
# 빈도수 처리
ko = nltk.Text(tokens_ko, name='대한민국 국회 의안 제 1809890호')
# returns number of tokens (document length)
print(len(ko.tokens))
# returns number of unique tokens (중복값을 뺀 토큰 수)
# set : 중복이 없는 집합함수 뽑아주는 메서드
print(len(set(ko.tokens)))
# 빈도수로 정리
# returns frequency distribution
ko.vocab()
plt.figure(figsize=(12,6))
ko.plot(50) # 상위 50개만 보여줘
plt.show()
# 불용어 처리
stop_words = ['.', '(', ')', ',', "'", '%', '-', 'X', ').', '×','의','자','에','안','번','호','을','이','다','만','로','가','를']
# 반복문으로 돌려서 불용어 모두 제거
ko = [each_word for each_word in ko if each_word not in stop_words]
ko
# 최종 결과는 리스트로 반환 됨
# 불용어 제거 후 그래프로 확인
ko = nltk.Text(ko, name='대한민국 국회 의안 제 1809890호')
plt.figure(figsize=(12,6))
ko.plot(50) # Plot sorted frequency of top 50 tokens
plt.show()
ko.count('초등학교')
plt.figure(figsize=(12,6))
# dispersion_plot : 텍스트 내 단어 사용 빈도와 위치를 분산 그래프로 그려줌
ko.dispersion_plot(['육아휴직', '초등학교', '공무원'])
# 단어주변부 확인
ko.concordance('초등학교')
# 연이어 사용된 단어 확인
ko.collocations()
# 시각화
data = ko.vocab().most_common(150)
# for winow : font_path='c:/Windows/Fonts/malgun.ttf'
# for mac : font_path='/Library/Fonts/AppleGothic.ttf'
wordcloud = WordCloud(font_path='c:/Windows/Fonts/malgun.ttf',
relative_scaling = 0.2,
background_color='white',
).generate_from_frequencies(dict(data))
plt.figure(figsize=(12,8))
plt.imshow(wordcloud)
plt.axis("off")
plt.show()