디지털

파이썬으로 네이버 검색API 요약문 수집 및 형태소 분석하기

kkwaks 2016. 4. 7. 08:00
반응형

네이버 검색API를 이용하여 검색 결과에 나오는 요약문을 가져와서 분석할 일이 있어서 파이썬으로 한 번 만들어 봤습니다. 확실히 파이썬은 라이브러리가 풍부하기 때문에 필요한 라이브러리를 이용해서 빠른시간안에 원하는 프로그램을 개발할 수 있다는 장점이 있는 것 같네요.



개발환경은 파이썬 2.7 버전이고 필요 라이브러리는 BeautifulSoup(XML 파서), konply(형태소 분석) 입니다. 윈도우에서 python 라이브러리 설치는 다음을 참고하시기 바랍니다.


1. pip 설치  get-pip.py 받아서 python get-pip.py 실행
2. 라이브러리 설치 
    python -m pip install beautifulsoup4
3. konply 설치방법은 공식 페이지 참조 http://konlpy.org/ko/v0.4.3/install/#id2
    Komoran 사용시 Jtype 에러 해결 위해 numpy도 추가 설치



블로그는 target 을 blog로 카페와 뉴스는 각각 cafearticle, news 로 변경해서 가져오면 됩니다. 블로그 검색API 옵션은 네이버 개발자 센터를 확인하시기 바랍니다. 

(http://developer.naver.com/wiki/pages/Blog)



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
# -*- coding: utf8 -*-
 
import urllib2
import csv
from bs4 import BeautifulSoup
from konlpy.tag import Komoran
komoran = Komoran()
 
import sys
reload(sys)
sys.setdefaultencoding('utf-8'#검색 문자열 한글이 깨지지 않도록 함
 
search_word = '검색문자열' #검색문자열
 
display = '100' #default 10, max 100
page = 400 #default 1, max 1000
key = '검색API이용key'
 
#블로그 글 가져오기
 
= csv.writer(open("naverblog.csv""w"),lineterminator='\n'#공백 row가 생기지 않도록 lineterminator옵션 추가
f.writerow(['\xEF\xBB\xBF']) #엑셀에서 csv열 때 utf-8인식하도록 
f.writerow(['desc','morph'])
 
for p in range(1,page):
    url = "http://openapi.naver.com/search?key=" + key + "&display="+display+"&target=blog&sort=sim&query=" + search_word.encode('utf-8'+ "&start="+str(p) ;
    request = urllib2.Request(url)
 
    response = urllib2.urlopen(request)
    blog = BeautifulSoup(response,"html.parser")
    
    
    for item in blog.findAll('item'):
        itemDesc = item.description.contents[0]
        
        #제거 문자열 
        itemDesc = itemDesc.replace('<b>','')
        itemDesc = itemDesc.replace('</b>','')
        itemDesc = itemDesc.replace('!','')
        itemDesc = itemDesc.replace('.','')
        
        itemMorph = komoran.pos(itemDesc) #코모란 형태소 분석 
        #print itemMorph
        strMorph = []
        for word in itemMorph: #형태소와 품사 합침
            strMorph.append('/'.join(word))
        strMorph = ' '.join(strMorph) #형태소 리스트 합침
        
        f.writerow([itemDesc,strMorph]) #CSV에 데이터 입력
 
    print 'blog_page:'+str(p)+','
 
cs



반응형