개인용 복습공간

[Python] 형태소 분석기 - konlpy 본문

Python

[Python] 형태소 분석기 - konlpy

taehwanis 2021. 6. 25. 19:15

 

 

 

text를 크롤링하고
konlpy를 이용해 형태소 분석을
해보려고 한다.

 

 

 

 

konlpy(코엔엘파이)는 한국어 정보처리를 위한 파이썬 라이브러리이다. 이것을 이용하여 크롤링해온 text를 분석해보려고 한다.

 

 

 

konlpy를 설치하기 전에 자바 JDK설치와 환경변수 설정과 JPype를 설치해줘야 한다. 그리고 Python3.9에서는 작동이 안돼서 3.7에서 작업을 했다. (과정 생략)

cmd창에서 pip install konlpy으로 설치가 가능하다.

konlpy 설치

 

 

 

일단 영상의 url과 제목을 가져올 테이블을 만든다.

textEX2 테이블

 

 

 

 

유튜버 영국 남자 채널의 영상들을 크롤링해 사용해보려 한다.
채널의 url과 title이 들이었는 path가 같아서 크롤링이 수월하다. 크롤링해온 title리스트를 for문을 이용하여 하나의 기다란 text처럼 붙여주는 작업을 했다.

그리고 konlpy의 Okt를 사용했다. nouns를 이용하여 명사만 추출하고 Counter로 한글 명사의 빈도를 계산하고 most_common(25)으로 25위까지 순위를 매겨 출력했다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import selenium
from selenium import webdriver
from time import sleep
import time 
import pymysql
from konlpy.tag import Okt
from collections import Counter
 
# 웹 드라이버 초기화
driver = webdriver.Chrome(executable_path='chromedriver')
driver.implicitly_wait(5)
 
conn = pymysql.connect(host="localhost",
                     user="root1234",
                     passwd="1234",
                     db="crawl_data",
                     charset="utf8")
curs=conn.cursor(pymysql.cursors.DictCursor)
 
#채널에서 동영상url 가져오는 함수
def get_videos_url():
    videos, titles = [], []
    idx1 = 1  
    start_url = "https://www.youtube.com/user/koreanenglishman/videos"
    driver.get(start_url)
 
    while True:
        try:
            path ='/html/body/ytd-app/div/ytd-page-manager/ytd-browse/ytd-two-column-browse-results-renderer/div[1]/ytd-section-list-renderer/div[2]/ytd-item-section-renderer/div[3]/ytd-grid-renderer/div[1]/ytd-grid-video-renderer[' + str(idx1) + ']/div[1]/div[1]/div[1]/h3/a'                     
            Video_url = driver.find_element_by_xpath(path)
            videos.append(Video_url.get_attribute('href'))
            titles.append(Video_url.get_attribute('title'))
 
            # 한 페이지에 약 30개 불러오는 데, 동영상 목록을 추가 불러오기 위해 스크롤 내림
            if idx1 % 30 == 0 :
                driver.execute_script('window.scrollBy(0, 4320);')
                time.sleep(1)
            idx1 += 1
 
        except Exception as e:
            print()
            print(e)
            break 
 
    driver.close()
    return videos, titles
 
videos_list, title_list = get_videos_url()
#비어있는 text
text=""
 
for i in range(0len(videos_list)):
    sql = """insert ignore into testex2(v_url, v_title) values (%s, %s)""" 
    curs.execute(sql, (videos_list[i], title_list[i]))
    conn.commit()
    print("<"+videos_list[i] +", " + title_list[i]+">")
 
    #text에 붙여주기
    text += title_list[i]
 
conn.close()
 
#
okt = Okt()
noun = okt.nouns(text)
count = Counter(noun)
noun_list = count.most_common(25)
print(noun_list)
cs

 

 

 

konlpy를 이용한 명사 추출이 깔끔하진 않지만 잘 작동하는 것 같다.

실행 후 TERMINAL

명사와 명사 사용빈도가 들어있는 투플 리스트를 얻었으니 최대 빈도의 명사만 몇 개만 추출하든 사전을 만들던지 등의 추후 응용은 쉽게 할 수 있을 것 같다.

 

실행 후 DB

Comments