def post(self): # try: print("LoadSrcFile start") def getKobilFilePath(path): return path.split('../data/')[1] input_doc_dir = '../../data/data/' + str( self.group_path) + '/doc/*.txt' doc_files = glob.glob(input_doc_dir) print("doc_file len : ", len(doc_files)) group = TB_GROUP.query.filter_by(group_name=self.group_path).first() cur = 0 for f in doc_files: # if cur > 0: # break cur += 1 doc_filepath = getKobilFilePath(f) topic_filepath = doc_filepath.replace('doc', 'topic') # print("doc_file : ", doc_filepath) # print("topic_file : ", topic_filepath) filename = os.path.basename(doc_filepath).split('.')[0] print("============================== start cur : ", cur, " filename : ", filename) # print("filename : ", filename) doc_ngrams = kobill.open(doc_filepath).read() docs_ko = self.ha.nouns(doc_ngrams) keywords = self.getKeywords(docs_ko) print("keywords : ", keywords) topic_ngrams = kobill.open(topic_filepath).read() topics_ko = self.ha.nouns(topic_ngrams) # print("topics_ko : ", topics_ko) sim_list = self.getSimList(keywords.split(','), docs_ko, topics_ko) # print("sim_list : ",sim_list) fk_f_idx = self.insert_file_info(group.idx, filename, doc_filepath, doc_ngrams, topic_ngrams, docs_ko, topics_ko) for sim in sim_list: print("key : ", sim['key']) print("query_idf : ", sim['query_idf']) f_k_idx = self.insert_keyword(group.idx, filename, fk_f_idx, sim['key'], sim['query_idf'], sim['query_idf']) print("f_k_idx : ", f_k_idx) f_s_idx = self.insert_sim_cos(group.idx, filename, sim['key'], fk_f_idx, f_k_idx, sim['sim_cos'], sim['topic_cos']) print("f_s_idx : ", f_s_idx) objects = [] Log("[LoadSrcFile SUCCESS]") return result(200, "LoadSrcFile successful.", objects, None, "by sisung ")
t.nouns(txt) t.pos(txt) import nltk from konlpy.corpus import kobill file_ko = kobill.fileids() #디렉토리를 찾아야한다 #윈도우 탐색 > kobill 검색 #C:\Users\stu\Anaconda3\Lib\site-packages\konlpy\data\corpus\kobill #예제파일 위치 찾아서 문재인태통령 취임사 > 열어서 다른이름으로 저장 > UTF-8로 kobill에 저장 doc_ko = kobill.open("문재인대통령취임사.txt").read() doc_ko from konlpy.tag import Twitter t = Twitter() tokens_ko = t.nouns(doc_ko) tokens_ko ko = nltk.Text(tokens_ko) #단어의 총 갯수 len(ko.tokens) #중복되는 것 제거 len(set(ko.tokens)) #단어의 건수 ko.vocab()
from konlpy.corpus import kobill # docs from pork.kr/bill from konlpy.tag import Twitter import nltk from matplotlib import font_manager, rc # matplotlib 한글폰트지정 font_name = font_manager.FontProperties( fname="c:/Windows/Fonts/malgun.ttf").get_name() rc('font', family=font_name) # 01. loading files_ko = kobill.fileids() #get file ids doc_ko = kobill.open('news.txt').read() # news.txt는 http://boilerpipe-web.appspot.com/ 를 통해 포탈뉴스 데이터를 수집 # news.txt 는 konlpy의 corpus 아래에 있는 kobill directory에 미리 저장되어있어야 함 # /Library/Python/2.7/site-packages/konlpy/data/corpus/kobill # 02. Tokenize t = Twitter() tokens_ko = t.morphs(doc_ko) # 03. Token Wapper 클래스 생성 (token에 대한 처리를 위해서임) ko = nltk.Text(tokens_ko, name='news') # name # 04. 토큰 정보 및 단일 토큰 정보 확인 # print(len(ko.tokens)) #returning number of tokens( document length) # print(len(set(ko.tokens))) #returns number of unique tokens ko.vocab() #returns frequency distribution # 05. chart
#!usr/bin/env python # -*- coding: utf-8 -*- # set default coding euc-kr 2 utf-8 import sys reload(sys) sys.setdefaultencoding('utf-8') print ("load") #load from kobill from konlpy.corpus import kobill #docs_ko =kobill.open('kobill/news.txt').read() docs_ko = [kobill.open(i).read() for i in kobill.fileids()] print ("tokenize") #tokenize from konlpy.tag import Twitter; t = Twitter() print ("tokenize1") pos = lambda d:['/'.join(p) for p in t.pos(d,stem=True,norm=True)] print ('tokenize2') texts_ko = [pos(doc) for doc in docs_ko] #texts_ko = pos(docs_ko) print ("train") import time now_time = time.time() #train from gensim.models import word2vec wv_model_ko = word2vec.Word2Vec(texts_ko,workers=16,negative=10,window=7,size=300) wv_model_ko.init_sims(replace=True)
# In[7]: print(r'Hello\nWorld') #r: raw data print('Hello\nWorld') # In[8]: from konlpy.corpus import kolaw data = kolaw.open('constitution.txt').read() print(len(data)) print(data[:100]) # In[10]: from konlpy.corpus import kobill data1 = kobill.open('1809890.txt').read()[:1000] #1809890.txt - 1809899.txt 가능 data1 # ## 5. 워드 클라우드 # In[11]: type(data) # In[12]: i = 20 print("i={:d}".format(i)) print("i=%d" % (i)) # In[13]:
def load_ko_stopwords(filename): with open(filename, "r", encoding="utf-8") as f: s = set([line.rstrip() for line in f]) return s def tokenize(txt): tokens = Komoran().morphs(txt) hangul = re.compile('[^\uac00-\ud7a3]+') stpwrds = load_ko_stopwords("ko_stopwords.txt") tokens = [hangul.sub('', i) for i in tokens] tokens = [i for i in tokens if len(i) > 0 and i not in stpwrds] return tokens #main tokens = [] for i in kobill.fileids(): tokens.append(tokenize(kobill.open(i).read())) for i in kolaw.fileids(): tokens.append(tokenize(kolaw.open(i).read())) config = { 'min_count': 2, 'size': 100, 'sg': 1, 'batch_words': 10000, 'iter': 20, 'workers': multiprocessing.cpu_count(), } embedding_model = Word2Vec(tokens, **config) print(embedding_model.most_similar(positive=tokenize('육아휴직'), topn=50))
from wordcloud import WordCloud import matplotlib.pyplot as plt from konlpy.corpus import kobill from konlpy.tag import Okt from collections import Counter import pytagcloud import nltk font_path = "c:/Windows/Fonts/malgun.ttf" print(kobill.fileids()) text = kobill.open('1809899.txt').read() # 300자 까지 # print(text) okt = Okt() nouns = okt.nouns(text) for noun in nouns: if len(noun) < 2: nouns.remove(noun) # count = Counter(nouns) text1 = nltk.Text(nouns) data1 = text1.vocab() data300 = data1.most_common(300) dic = dict(data300) wc = WordCloud(width=1000,
# gutenberg corpus : 소설 말뭉치. nltk.download() # Korpus를 다운받을 수 있는 GUI창을 띄워줌. nltk.download("brown")을 치면 GUI가 뜨지 않고 다운로드됨. (※ 다운로드는 최초 1회만 하면 됨) # ------------------------------------------------- Konlpy 사용해보기 --------------------------------------------------------------------- ma = Kkma() print(ma.pos("오늘은 불금입니다.")) # 테스트 print(kolaw.fileids()) # txt 하나만 있음. print(kobill.fileids()) # 의안과 관련된 txt파일 10개 제공 c = kolaw.open(kolaw.fileids()[0]).read() # 파일포인터를 통해 첫번째 파일 오픈 print(len(c)) # 18884개의 character를 갖고 있음. print(len(c.split())) # 몇 개의 어절이 있는지 확인해보기(단순 띄어쓰기로 세었기때문에 중복 허용.) (4178개/정식 corpus는 보통 100만~1000만 단위의 어절 제공.) print(len(c.splitlines())) # 몇 개의 엔터가 들어가 있는지 확인 d = kobill.open(kobill.fileids()[0]).read() print(d.splitlines()[:2]) # 처음 두 요소만 출력 # ------------------------------------------------------------------------------------------------------------------------------------------- # ------------------------------- NLTK 말뭉치 사용해보기(brown, gutenberg corpus) ---------------------------------------- print(len(brown.fileids())) a = brown.open(brown.fileids()[0]).read() print(len(a), len(a.split()), len(a.splitlines()), a.splitlines()[:3]) b = gutenberg.open(gutenberg.fileids()[0]).read() print(len(b), len(b.split()), len(b.splitlines()), b.splitlines()[:3]) # ------------------------------------------------------------------------------------------------------------------------
from konlpy.corpus import kolaw, kobill #kolaw : 한국 법률 말뭉치 'constitution.txt'로 저장됨 #kobill : 대한민국 국회 의안 말뭉치. '1809890.txt ~ 1809899.txt' kolaw.open('constitution.txt').read()[:100] kobill.open('1809890.txt').read() import re text = "wow, it is awesome" re.search("(\w+)", text)
# Corpus (말뭉치) : 언어의 표본을 담아둔 묶은(사전) from konlpy.corpus import kobill # 정치 관련 사전 # 파일 읽어오기 (1) files_ko = kobill.fileids() # print(files_ko) # 문서 확인하기. # 파일 읽어오기 (2) doc_ko = kobill.open(r'mynews.txt').read() # print(doc_ko) # 의미 단어 추출 (Tokenize) from konlpy.tag import Okt t = Okt() tokens_ko = t.morphs(doc_ko) # 문서를 token으로 분리 print(tokens_ko) import nltk ko = nltk.Text(tokens_ko, name='원내대표') # 그런 단어가 있는지 검색할때 쓰는 nltk.Text print(ko) print('토큰 정보 확인-----') print(len(ko.tokens)) # 608개 print(len(set(ko.tokens))) #유니크한개 293개 fre_dist = ko.vocab() print(fre_dist) # <FreqDist with 293 samples and 608 outcomes> # from matplotlib import rc # rc('font', family='malgun gothic') # ko.plot(50)
''' Created on 2018. 11. 20. 문자열 자르고 의미 단어 검출 후 워드클라우드 출력 ''' from konlpy.corpus import kobill from anaconda_navigator.utils.encoding import write files_ko = kobill.fileids() doc_ko = kobill.open("news.txt").read() #print(doc_ko) from konlpy.tag import Okt t = Okt() tokens_ko = t.morphs(doc_ko) # Tokenize. print(tokens_ko) import nltk ko = nltk.Text(tokens_ko, name="뉴스") print(ko) print() print(len(ko.tokens)) # 토큰 갯수 684. print(len(set(ko.tokens))) # Set으로 중복 제거. 고유 토큰 수. fre_dist = ko.vocab() print(fre_dist) # <FreqDist with 303 samples and 684 outcomes>.
from konlpy.corpus import kolaw, kobill print(kolaw.fileids(), kobill.fileids()) # 헌법 전문 c = kolaw.open('constitution.txt').read() print(c[:40]) print('--------------------------------------------------------') # 국회 속기록 k = kobill.open('1809899.txt').read() print(k[:300])
#!/usr/bin/env python # -*- coding: utf-8 -*- from konlpy.corpus import kobill # Docs from pokr.kr/bill files_ko = kobill.fileids() # Get file ids doc_ko = kobill.open('test.txt').read() # news.txt는 http://boilerpipe-web.appspot.com/ 를 통해 포탈뉴스 부분에서 긁어왔다. # news.txt 는 konlpy의 corpus아래에 있는 kobill directory에 미리 저장되어있어야 한다. # /Library/Python/2.7/site-packages/konlpy/data/corpus/kobill 2.Tokenize (의미단어 검출) from konlpy.tag import Twitter; t = Twitter() tokens_ko = t.morphs(doc_ko) 3. Token Wapper 클래스 만들기(token에대해 이런 저런 처리를 하기 위해) import nltk ko = nltk.Text(tokens_ko, name='뉴스') 4. 토근 정보및 단일 토큰 정보 알아내기 print(len(ko.tokens)) # returns number of tokens (document length) print(len(set(ko.tokens))) # returns number of unique tokens ko.vocab() # returns frequency distribution #!/usr/bin/env python # -*- coding: utf-8 -*- import sys reload(sys) sys.setdefaultencoding('utf-8')
import importlib from konlpy.corpus import kobill docs_ko = [kobill.open(i).read() for i in kobill.fileids()] from konlpy.tag import Mecab t = Mecab(dicpath="C:/mecab/mecab-ko-dic") pos = lambda d: ['/'.join(p) for p in t.morphs(d)] texts_ko = [pos(doc) for doc in docs_ko] from gensim.models import word2vec wv_model_ko = word2vec.Word2Vec(texts_ko) wv_model_ko.init_sims(replace=True) wv_model_ko.save('ko_word2vec_e.model') print(wv_model_ko.most_similar(pos('기가지니')))
import nltk from konlpy.corpus import kobill files_ko = kobill.fileids() doc_ko = kobill.open("1809890.txt").read() from konlpy.tag import Okt t = Okt() token_ko = t.nouns(doc_ko) ko = nltk.Text(token_ko, name="대한민국 국회 의안 제 1809890호") import matplotlib.pyplot as plt path = "C:/Windows/Fonts/210 맨발의청춘L.ttf" from matplotlib import font_manager, rc font_name = font_manager.FontProperties(fname=path).get_name() rc("font", family=font_name) #plt.figure(figsize=(12,6)) #ko.plot(50) #plt.show() stop_words = [ ".", "(", ")", ",", "'", "%", "-", "X", ").", "x", "의", "자", "에", "안", "번", "호", "을", "이", "다", "만", "로", "가", "를" ] ko = [each_word for each_word in ko if each_word not in stop_words] ko = nltk.Text(ko, name="대한민국 국회 의안 제 1809890호") #plt.figure(figsize=(12,6))
print(wc.words_) # 단어의 빈도수 # print(type(wc.words_)) # for key in wc.words_.keys(): # print(key, ":", wc.words_[key]) wc.to_file('starwars.png') plt.figure(figsize=(8, 8)) # 그래프의 크기설정 plt.imshow(wc) # wordcloud를 그래프에 부착 plt.axis('off') # x, y축을 나타나지 않도록 설정 plt.show() # "육아휴직 법안 제 18098990호" 에 대한 wordcloud를 이용한 시각화 import nltk from konlpy.corpus import kobill doc_ko = kobill.open('1809890.txt').read() # doc_ko = open(data1/hong.txt', 'r', encoding='utf8').read() # doc_ko = open('contents_text.txt', 'r', encoding='utf8').read() print(doc_ko) # Okt 분석기로 명사 추출 from konlpy.tag import Okt t = Okt() tokens_ko = t.nouns(doc_ko) print(tokens_ko) ko = nltk.Text(tokens_ko) # # contents_text.txt 파일에서 # print(len(ko.tokens)) # 수집된 단어의 총갯수 : 253669 # print(len(set(ko.tokens))) # 중복을 제외한 단어 갯수 : 9679
from konlpy.tag import Twitter t = Twitter() t.nouns(txt) t.pos(txt) import nltk from konlpy.corpus import kobill file_ko = kobill.fileids() # 문재인 대통령 취임사 분석 # kobill 검색 - 폴더찾아가기 - 문재인 연설 복붙 (여기서 window 파일 그대로 받으면 오류) doc_ko = kobill.open("moon.txt").read() doc_ko # 문서 내용 확인하기 from konlpy.tag import Twitter t = Twitter() tokens_ko = t.nouns(doc_ko) # 명사 tokens_ko ko = nltk.Text(tokens_ko) len(ko.tokens) len(set(ko.tokens)) ko.vocab()
predict_pos_neg("심심해") predict_pos_neg("기뻐!! 신나!!") predict_pos_neg("슬퍼 죽겠다") predict_pos_neg("우울해") # http://blog.naver.com/PostView.nhn?blogId=2feelus&logNo=220384206922&redirect=Dlog&widgetTypeCall=true # [출처] 한글을 이용한 데이터마이닝및 word2vec이용한 유사도 분석|작성자 IDEO (참고하여 소스 커스터마이징) # 1. 읽기 #!/usr/bin/env python # -- coding: utf-8 -- from konlpy.corpus import kobill # Docs from pokr.kr/bill files_ko = kobill.fileids() # Get file ids # news.txt는 http://boilerpipe-web.appspot.com/ 를 통해 포탈뉴스 부분에서 긁어왔다. # news.txt 는 konlpy의 corpus아래에 있는 kobill directory에 미리 저장되어있어야 한다. # /Library/Python/2.7/site-packages/konlpy/data/corpus/kobill doc_ko = kobill.open('ratings_train.txt').read() # 2.Tokenize (의미단어 검출) from konlpy.tag import Okt import os import json # 학습시간이 오래 걸리므로 파일로 저장하여 처리 한다. if os.path.isfile('tokens_ko_morphs.txt'): with open('tokens_ko_morphs.txt', encoding='UTF8') as f: tokens_ko_morphs = json.load(f) else: okt = Okt() tokens_ko_morphs = okt.morphs(doc_ko) # JSON 파일로 저장
# 1. 읽기 #!/usr/bin/env python # -- coding: utf-8 -- import sys import importlib importlib.reload(sys) from konlpy.corpus import kobill # Docs from pokr.kr/bill files_ko = kobill.fileids() # Get file ids # news.txt는 http://boilerpipe-web.appspot.com/ 를 통해 포탈뉴스 부분에서 긁어왔다. # news.txt 는 konlpy의 corpus아래에 있는 kobill directory에 미리 저장되어있어야 한다. # /Library/Python/2.7/site-packages/konlpy/data/corpus/kobill doc_ko = kobill.open('ratings_train.txt').read() # 2.Tokenize (의미단어 검출) from konlpy.tag import Okt import os import json # 학습시간이 오래 걸리므로 파일로 저장하여 처리 한다. if os.path.isfile('tokens_ko_morphs.txt'): with open('tokens_ko_morphs.txt', encoding='UTF8') as f: tokens_ko_morphs = json.load(f) else: okt = Okt() tokens_ko_morphs = okt.morphs(doc_ko) # JSON 파일로 저장 with open('tokens_ko_morphs.txt', 'w', encoding="utf-8") as make_file: json.dump(tokens_ko_morphs, make_file, ensure_ascii=False, indent="\t")