해당 문장이 긍정인지 부정인지 판단하는 프로그램~ (실은 홈페이지로 만들려고 했으나..... 한글 형태소 분석에 자원을 너무 많이 써서 서버가 멈추는... 돈이 없어서 가장 성능 낮은 서버를 쓰고 있으니..프로그램 하나 안돌아간......ㅜㅡㅜ)
먼저 조건부 확률은 (https://ko.wikipedia.org/wiki/%EC%A1%B0%EA%B1%B4%EB%B6%80_%ED%99%95%EB%A5%A0 )
확률 공간 Ω에서의 두 사건 A, B에 대해서
일 때 사건 B가 일어났을 때 사건 A의 조건부 확률은
긍정 부정 두가지 상황이 있으므로
P(c) = 1/2
P1(x|c) = count(해당 문장에서 긍정 단어 리스트 수 ) / count(전체 긍정 단어 리스트 수 )
P2(x|c) = count(해당 문장에서 부정 단어 리스트 수 ) / count(전체 부정 단어 리스트 수 )
if p1 > p2:
긍정
else:
부정
이 된다.
자세한 사항은 http://newpower.tistory.com/127 참조
from konlpy.tag import Kkma
import pymysql
conn = pymysql.connect(host='127.0.0.1', user='root', passwd='123qwe', db='word', charset='utf8')
cur = conn.cursor()
kkma = Kkma()
#조건부 확률 계산
def conditional_probability(test, train_table, all_count, table_count):
counter = 0
list_count = []
#해당 문장이 해당 테이블에 존재 하는지 확인
for word in test:
cur.execute("SELECT count(*) as cnt FROM "+train_table+" where word = '"+word+"'")
for cnt in cur:
if int(cnt[0]) > 0:
counter += 1
list_count.append(counter)
counter = 0
print(list_count)
cal_list = []
for j in range(len(list_count)):
#다음에 * 연산할떄 0이 되지 않기 위해 +1을 해줌
cal_list.append((list_count[j]+1)/float(table_count+all_count))
result = 1
for j in range(len(cal_list)):
result *= float(round(cal_list[j], 6))
return_value = float(result)*float(1.0/2.0)
print(return_value)
return return_value
# get the data
input_file = open('input.txt', 'r')
list_positive = []
list_negative = []
#형태소 분리
input_line = input_file.readline()
input_kkma = kkma.pos(input_line)
print(input_kkma)
test_output = []
for i in input_kkma:
test_output.append(i[0])
#긍정 단어 전체 갯수
cur.execute("SELECT count(*) as cnt FROM positive ")
positive_count = 0
for response in cur:
positive_count = int(response[0])
#부정 단어 전체 갯수
cur.execute("SELECT count(*) as cnt FROM negative ")
negative_count = 0
for response in cur:
negative_count = int(response[0])
# naive bayes 값 계산
result_pos = conditional_probability(test_output, 'positive', positive_count+negative_count, positive_count)
result_neg = conditional_probability(test_output, 'negative', positive_count+negative_count, negative_count)
if result_pos > result_neg:
print(u'긍정')
else:
print(u'부정')
결과
" 너는 아름답다." 는 다음과 같이 나옵니다.
끝.
'app > python' 카테고리의 다른 글
| python timeit 함수 수행 시간 알아내기 (0) | 2016.05.20 |
|---|---|
| TRAVIS 연동 (python) (0) | 2016.05.19 |
| gensim을 설치여정 (ubuntu 14.04) (0) | 2016.04.05 |
| JetBrains edit font size control (0) | 2014.10.23 |
| python dict in list sort to dict value (0) | 2014.10.17 |