본문 바로가기
파이썬

파이썬 프로젝트(2) : KoalaNLP으로 키워드 추출해내기

by 스노위13 2022. 9. 23.

1. 내용 : 펀딩 사이트의 제목에서 유의미한 키워드를 추출하였다. 그리고 이 키워드를 flask를 사용해서 각각의 펀딩 페이지에 넘겨 주었다.

2. 특이점 : 유의미한 키워드를 추출하기 위해 문장구조 단위로 분석을 한 뒤 주어와 목적어만 추출하여 품사 단위 중 명사만 추출해내게 하였다. KoalaNLP에 있는 분석기 중 꼬꼬마 구문 분석기로 문장 구조 단위로 나누었고 hannanum로 명사만 추출해냈다. 다만 펀딩 사이트의 제목의 경우 고유명사와 신조어가 많이 섞여 있어서 그 부분이 제대로 분석되지 못해 아쉬웠다. 

(참고 사이트 : https://koalanlp.github.io/python-support/html/index.html)

3. 코드 및 화면 
1) 화면

2) 파이썬 코드

from koalanlp.Util import initialize, finalize
from koalanlp.proc import Parser
from koalanlp import API
import mydb
from konlpy.tag import *
import cx_Oracle

db = mydb.Mydb()
hannanum = Hannanum()
komoran = Komoran()

initialize(KKMA='LATEST')  #: HNN=2.0.4, ETRI=2.0.4

conn = cx_Oracle.connect('yoonsool', 'yoonsool', 'localhost:1521/XE')

with conn:
    cur = conn.cursor()
    cur.execute("""
    SELECT fu_no
    FROM funding
    """)
    rows = cur.fetchall()
    fundings = rows

    for i in fundings:
        sql2 = """
        SELECT fu_title, fu_cate
        FROM funding
        WHERE fu_no = :1
        """
        fu_no = i[0]
        print(i)
        dbf = db.get_select_param(sql2, [fu_no])[0]
        title = dbf[0]
        category = dbf[1]
        print(title)
        print(category)

        parser = Parser(API.KKMA)

        text = title.strip()
        obj = ''
        undef = ''
        sentences = parser(text)

        for sent in sentences:
            print("===== Sentence =====")
            dependencies = sent.getDependencies()
            if len(dependencies) > 0:
                for edge in dependencies:
                    # 목적어
                    if str(edge.getDepType()) == 'OBJ':
                        obj += ' '
                        obj += edge.getDependent().getSurface()
                    #주어, 서술어
                    if str(edge.getDepType()) == 'UNDEF':
                        undef += ' '
                        undef += edge.getDependent().getSurface()

            else:
                print("(Unexpected) NULL!")
        # 주어, 서술어, 목적어만 가지고 옴
        result = obj + ' ' + undef

        #명사만 추출 (set으로 중복값 제거)
        temp = set(hannanum.nouns(result))
        string = ' '.join(temp)
        print(string)
        print(type(string))

        cnt = db.fn_insert("""
        INSERT INTO funding_search2 (
            fu_no            , keyword
        ) VALUES (
            :v0             , :v1
        )
        """, [fu_no, string])

        print(cnt)

finalize()

3) jsp 코드(일부)

<div class="fu_detail" id="keyword"></div>

<script type="text/javascript">
let fuNo = $("form[name='addLike']").find('#fuNo').val();
let str="";

$(function(){
	fn_funding_keyword();
});	

function fn_funding_keyword(){
	$.ajax({
		url : "http://192.168.0.25:5000/keywordtag/"
		, data:{fuNo : fuNo}
		, success: function(data) {
    	   console.log(data);
    	   str+='<h5>';
    	   for(let i in data) {
      		   str+=' #'+ data[i];		   
			};
			str+='</h5>';
			$("#keyword").append(str);
		},
		error : function() {
			console.log('error');
      }		
	}); //ajax
}

</script>

 

댓글