도찐개찐

[머신러닝-마이닝] 06. KoNLPy 본문

PYTHON/데이터분석

[머신러닝-마이닝] 06. KoNLPy

도개진 2023. 1. 4. 10:51

KoNLPy

  • NLTK는 영어 정보처리를 위한 패키지
  • 반면, KoNLPy는 한국어 정보처리를 위한 패키지임
  • 서울대학교 산업공학과 개발한 형태소 분석기
    • 이미 개발된 한글 형태소 분석기를 파이썬에서 바로 사용할 수 있도록 도와줌
    • 일종의 래퍼 패키지
  • 현재까지 지원하는 형태소분석기는 모두 5가지
    • Hannanum, Kkma, Komoran, mecab, Okt
  • konlpy-ko.readthedocs.io / konlpy.org

설치방법

  • KoNLPy 설치전 필수 패키지가 JPype1 인데 Visual C++ 14 버젼 필요!! (OS가 윈도우인 경우)
  • Many binaries depend on numpy+mkl and the current Microsoft Visual C++ Redistributable for Visual Studio 2015-2022 for Python 3
    • 하지만, 미리 컴파일된 패키지가 배포됨
    • www.lfd.uci.edu/~gohlke/pythonlibs 에서 JPype1 패키지를 다운로드한 후 설치함
    • pip install JPype1-1.4.0-cp38-cp38m-win_amd64.whl (22-08-31)
    • pip install konlpy
# !pip install konlpy
Requirement already satisfied: konlpy in /home/bigdata/.py39/lib/python3.9/site-packages (0.6.0)
Requirement already satisfied: numpy>=1.6 in /home/bigdata/.py39/lib/python3.9/site-packages (from konlpy) (1.23.4)
Requirement already satisfied: JPype1>=0.7.0 in /home/bigdata/.py39/lib/python3.9/site-packages (from konlpy) (1.4.1)
Requirement already satisfied: lxml>=4.1.0 in /home/bigdata/.py39/lib/python3.9/site-packages (from konlpy) (4.9.1)
Requirement already satisfied: packaging in /home/bigdata/.py39/lib/python3.9/site-packages (from JPype1>=0.7.0->konlpy) (21.3)
Requirement already satisfied: pyparsing!=3.0.5,>=2.0.2 in /home/bigdata/.py39/lib/python3.9/site-packages (from packaging->JPype1>=0.7.0->konlpy) (3.0.9)
import konlpy

from konlpy.tag import Okt          # 구 twitter
from konlpy.tag import Kkma
# 트위터 형태소 사전을 사용하기 위해 초기화
kkma = Kkma()
twitter = Okt()
txt1 = '아버지가 방에 들어가신다.'
txt2 = '나는 보리밥을 먹었다.'
txt3 = '롯데마트가 판매하고 있는 흑마늘 양념 치킨이 논란이 되고 있다.'
# 형태소 분석1 : pos, 중요 품사 기반 추출
twitter.pos(txt1)
[('아버지', 'Noun'),
 ('가', 'Josa'),
 ('방', 'Noun'),
 ('에', 'Josa'),
 ('들어가신다', 'Verb'),
 ('.', 'Punctuation')]
kkma.pos(txt1)
[('아버지', 'NNG'),
 ('가', 'JKS'),
 ('방', 'NNG'),
 ('에', 'JKM'),
 ('들어가', 'VV'),
 ('시', 'EPH'),
 ('ㄴ다', 'EFN'),
 ('.', 'SF')]
twitter.nouns(txt1),\
twitter.nouns(txt2),\
twitter.nouns(txt3)
(['아버지', '방'], ['나', '보리밥'], ['롯데', '마트', '판매', '흑마', '늘', '양념', '치킨', '논란'])
kkma.nouns(txt1),\
kkma.nouns(txt2),\
kkma.nouns(txt3)
(['아버지', '방'],
 ['나', '보리밥'],
 ['롯데', '롯데마트', '마트', '판매', '흑', '흑마늘', '마늘', '양념', '치킨', '논란'])

konlpy 내장 한국어 말뭉치

  • 대한민국 헌법 말뭉치 : kolaw
  • 국회법안 말뭉치 : kobill
from konlpy.corpus import kolaw
from konlpy.corpus import kobill

doc1 = kolaw.open('constitution.txt').read()
print(doc1[:100])       # 100 자까지 확인
대한민국헌법

유구한 역사와 전통에 빛나는 우리 대한국민은 3·1운동으로 건립된 대한민국임시정부의 법통과 불의에 항거한 4·19민주이념을 계승하고, 조국의 민주개혁과 평화적 통일의
doc2 = kobill.open('1809895.txt').read()
print(doc2[:100])       # 100 자까지 확인
하도급거래 공정화에 관한 법률 일부개정법률안

(유선호의원 대표발의 )

 의 안
 번 호

9895

발의연월일 : 2010.  11.  15.

발  의  자 : 유선호․강기갑

대한민국 헌법 말뭉치 워드클라우드

  • 한글폰트는 font_path 속성으로 설정
import konlpy

from konlpy.tag import Okt          # 구 twitter
from konlpy.tag import Kkma
from nltk import FreqDist
from wordcloud import WordCloud
import matplotlib.pyplot as plt
from collections import Counter
import matplotlib as mpl
import numpy as np
from PIL import Image
# 트위터 형태소 사전을 사용하기 위해 초기화
kkma = Kkma()
twitter = Okt()
# mask_path = '../img/h.jpg'       # 투명성 없는 파일
# mask = np.array(Image.open(mask_path))   # 배경 이미지 파일을 numpy 배열로 변환

wc = WordCloud(background_color='white',
              width=640, height=480, font_path='/home/bigdata/py39/lib/python3.9/site-packages/matplotlib/mpl-data/fonts/ttf/NanumGothic.ttf').generate_from_text(doc1)
plt.imshow(wc, interpolation='bilinear')
plt.axis('off')
plt.show()
---------------------------------------------------------------------------

NameError                                 Traceback (most recent call last)

Cell In [9], line 5
      1 # mask_path = '../img/h.jpg'       # 투명성 없는 파일
      2 # mask = np.array(Image.open(mask_path))   # 배경 이미지 파일을 numpy 배열로 변환
      4 wc = WordCloud(background_color='white',
----> 5               width=640, height=480, font_path='/home/bigdata/py39/lib/python3.9/site-packages/matplotlib/mpl-data/fonts/ttf/NanumGothic.ttf').generate_from_text(doc1)
      6 plt.imshow(wc, interpolation='bilinear')
      7 plt.axis('off')


NameError: name 'doc1' is not defined

허준이 교수 서울대 졸업 축사 워드클라우드

f = open('../data/jun_speech.txt', 'r')
speech = f.read()
# speech
f.close()
speech_nouns = [t for t in twitter.nouns(speech) if len(t) >= 2]
# doc_speech = [w[0] for w in speech_nouns if w[1] in 'Noun']
mask_path = '../img/h.jpg'       # 투명성 없는 파일
mask = np.array(Image.open(mask_path))   # 배경 이미지 파일을 numpy 배열로 변환

wc = WordCloud(background_color='white',
              width=640, height=480, font_path='/home/bigdata/py39/lib/python3.9/site-packages/matplotlib/mpl-data/fonts/ttf/NanumGothic.ttf').generate_from_text(' '.join(speech_nouns))

plt.imshow(wc, interpolation='bilinear')
plt.axis('off')
plt.show()

다양한 색상팔레트를 이용한 워드클라우드

  • jiffyclub.github.io/palettable
  • 여러가지 배색을 사용하는데 도와주는 패키지
    • pip install palettable
    • pip install colorbrewer
  • 색상팔레트 유형
    • sequential : 수치데이터, 순서가 있는 데이터
    • qualitative : 범주형 데이터
    • diverging : 수치형/범주형 데이터
!pip install palettable colorbrewer
Requirement already satisfied: palettable in /home/bigdata/.py39/lib/python3.9/site-packages (3.3.0)
Requirement already satisfied: colorbrewer in /home/bigdata/.py39/lib/python3.9/site-packages (0.2.0)
Requirement already satisfied: six in /home/bigdata/.py39/lib/python3.9/site-packages (from colorbrewer) (1.16.0)
import konlpy

from konlpy.tag import Okt          # 구 twitter
from konlpy.tag import Kkma
import random
from palettable.colorbrewer.sequential import Reds_9
from palettable.colorbrewer.diverging import RdYlBu_11
from palettable.colorbrewer.qualitative import Pastel2_8

def color_func(word, font_size, position,
              orientation, random_state=None, **kwargs):
    return tuple(RdYlBu_11.colors[random.randint(0, 10)])
    #return tuple(Reds_9.colors[random.randint(0, 8)])
    # return tuple(Pastel2_8.colors[random.randint(0, 7)])
mask_path = '../img/h.jpg'       # 투명성 없는 파일
mask = np.array(Image.open(mask_path))   # 배경 이미지 파일을 numpy 배열로 변환

wc = WordCloud(background_color='white',
              width=640, height=480, font_path='/home/bigdata/py39/lib/python3.9/site-packages/matplotlib/mpl-data/fonts/ttf/NanumGothic.ttf').generate_from_text(' '.join(speech_nouns))\
            .recolor(color_func=color_func)

plt.imshow(wc, interpolation='bilinear')
plt.axis('off')
plt.show()

728x90
Comments