# 텍스트 마이닝 : 수많은 텍스트에서 의미있는 데이터만 추려 내는 행위 print('전체 확인하기') for myitem in result: somedata = f'단어 : {myitem[0]}, 품사 : {myitem[1]}' print(somedata) print('-' * 30) print('2글자 이상의 명사만 추출해보기') only_nouns = [] for myitem in result: if (myitem[1] in ['NNG', 'NNP']): if(len(myitem[0]) >= 3): somedata = f'단어 : {myitem[0]}, 품사 : {myitem[1]}' only_nouns.append(myitem[0]) else: print(myitem[0] + '은 제외합니다.') print(only_nouns) ############# print('명사만 추출해보기') nouns = komo.nouns(text) print(nouns) ############# # userdic 매개 변수 : 사용자 정의 사전을 활용하는 방법 sentence = '국정 농단 태블릿 PC, 최성연, 가나다라' komo = Komoran(userdic='user_dic.txt') print(komo.pos(sentence)) print('-' * 30)
sys.setdefaultencoding('utf-8') import json import operator import urllib2 import requests from konlpy.tag import Komoran import collections komoran = Komoran() allTitle = urllib2.urlopen("http://polatics.news/all").read().split('\n') allTitle = "\n".join([" ".join(komoran.nouns(t)) for t in allTitle]) vocaAll = allTitle.split() print (len(vocaAll)) # 길이 1 이하인 것을 제외만 해도, 상당한 노이즈를 제거할 수 있다 vocaAll = [v.strip() for v in vocaAll if len(v) > 1] # result ; list of tuple # 모든 애들에 대해서 할필요가 전혀 없다. # 유용하지 못한 관계만 추가될 것 같다 voca_topK = collections.Counter(vocaAll).most_common(300) vocabulary = [] reverse_index = {} for i in voca_topK:
line=path.read() line = line.replace("'","").replace("?","").replace(".","").replace("'","").replace('"' ,"").replace("!","").replace("-","").replace('"',"").replace("\n","") print(line) if not line: break line = re.sub("\n","", line).strip() if line == "" : continue words = komoran.nouns(line) if len(words) == 0: continue result.append(words) except Exception as e: continue print(result) for b in result: for w in b: print(w,end="\t") print("")
from konlpy.tag import Komoran print("Dsds") komoran = Komoran() print(komoran.morphs(u'우왕 코모란도 오픈소스가 되었어요')) print(komoran.nouns(u'오픈소스에 관심 많은 멋진 개발자님들!')) print(komoran.pos(u'한글형태소분석기 코모란 테스트 중 입니다.'))
from konlpy.tag import Okt okt = Okt() import sys file = open('output.txt', 'r', encoding='utf8') data = file.read().split('**') chosen_num = [0, 0, 0] #print(data) for i in range(1, len(data)): a = data[i].split(']')[1] print(i, '/', len(data) - 1) print('1. hannaum') print(hannanum.nouns(a)) print('2. komoran') print(komoran.nouns(a)) print('3. okt') print(okt.nouns(a)) print('원본') print(a) while (1): choose = input("숫자를 입력하세요(오류시 0) : ") if choose == '0': continue if choose == '1' or choose == '2' or choose == '3': break chosen_num[int(choose) - 1] += 1 total = chosen_num[0] + chosen_num[1] + chosen_num[2] print('1. hannaum') print(chosen_num[0] / total * 100, '%')
ngrams = [text[x:x + num_gram] for x in range(0, len(text))] return tuple(ngrams) def similarity(doc1, doc2): cnt = 0 for token in doc1: if token in doc2: cnt = cnt + 1 return cnt/len(doc1) sentence1 = '6월에 뉴턴은 선생님의 제안으로 트리니티에 입학했다.' sentence2 = '6월에 뉴턴은 선생님의 제안으로 대학교에 입학했다.' sentence3 = '나는 맛있는 밥을 뉴턴 선생님과 함께 먹었다.' komoran = Komoran() bow1 = komoran.nouns(sentence1) bow2 = komoran.nouns(sentence2) bow3 = komoran.nouns(sentence3) # 단어 n-gram 토큰 출력 doc1 = word_ngram(bow1, 2) doc2 = word_ngram(bow2, 2) doc3 = word_ngram(bow3, 2) print(doc1) print(doc2) r1 = similarity(doc1, doc2) r2 = similarity(doc3, doc1) print(r1)
from konlpy.tag import Komoran import numpy as np komoran = Komoran() text = "오늘 날씨는 구름이 많아요." # 명사만 추출 nouns = komoran.nouns(text) print(nouns) # 단어 사전 구축 및 단어별 인덱스 부여 dics = {} for word in nouns: if word not in dics.keys(): dics[word] = len(dics) print(dics) # 원-핫 인코딩 nb_classes = len(dics) targets = list(dics.values()) one_hot_targets = np.eye(nb_classes)[targets] print(one_hot_targets)
def read_review_data(filename): with open(filename, 'r', encoding='UTF-8') as f: data = [line.split('\t') for line in f.read().splitlines()] data = data[1:] return data start = time.time() print('1) 말뭉치 데이터 읽기 시작') review_data = read_review_data( 'C:/Users/obybk/OneDrive/바탕 화면/인공지능/deepChat/Tokenizing/ratings.txt') print(len(review_data)) print('1) 말뭉치 데이터 읽기 완료: ', time.time() - start) print('2) 형태소에서 명사만 추출 시작') komoran = Komoran() docs = [komoran.nouns(sentence[1]) for sentence in review_data] print('2) 형태소에서 명사만 추출 완료: ', time.time() - start) #word2Vec 모델 학습 print('3) 모델학습 시작') model = Word2Vec(sentences=docs, size=200, window=4, hs=1, min_count=2, sg=1) print('3) Word2Vec 모델 학습 완료: ', time.time() - start) # 모델 저장 print('4) 학습된 모델 저장 시작') model.save('nvmc.model') print('4) 학습된 모델 저장 완료: ', time.time() - start) # 학습된 말뭉치 수, 코퍼스 내 전체 단어 수 print("corpus_count : ", model.corpus_count) print("corpus_total_words : ", model.corpus_total_words)
pyplot.savefig(filename) # In[56]: komoran = Komoran() doc='' with open('D:\\work\\nlp\\test.csv','r',encoding='utf-8') as f : rdr = csv.reader(f) r = list(rdr)#csv.reader객체를 리스트로 for line in r : #print(line) doc +="".join(line)+","#line이 각각 list인데, 멤버가 1개 밖에 없어서 join을 어떤형태로 해도 같음. tagged_word = komoran.nouns(doc) cnt = Counter(tagged_word) #dictionary 값으로 만들어줌. print('nchars : ',len(doc)) print('ntokens : ',len(tagged_word)) print(cnt.most_common(100)) #pprint(cnt.most_common(50)) draw_zipf(cnt.values(), 'zipf.png') print(sorted(cnt.values(),reverse =True)) # In[ ]: