from collections import Counter from konlpy.corpus import kolaw from konlpy.tag import Hannanum from konlpy.plot import draw_zipf from konlpy.utils import concordance, pprint from matplotlib import pyplot def draw_zipf(count_list, filename, color='blue', marker='o'): sorted_list = sorted(count_list, reverse=True) pyplot.plot(sorted_list, color=color, marker=marker) pyplot.xscale('log') pyplot.yscale('log') pyplot.savefig(filename) doc = kolaw.open('constitution.txt').read() pos = Hannanum().pos(doc) cnt = Counter(pos) print 'nchars :', len(doc) print 'ntokens :', len(doc.split()) print 'nmorphs :', len(set(pos)) print '\nTop 20 frequent morphemes:'; pprint(cnt.most_common(20)) print '\nLocations of "대한민국" in the document:' concordance(u'대한민국', doc, show=True) draw_zipf([b for a, b in cnt.items()], 'zipf.png')
def test_utils_concordance_show(capsys): from konlpy.corpus import kolaw from konlpy.utils import concordance doc = kolaw.open('constitution.txt').read() ccd = concordance(u'대한민국', doc, show=True) out, err = capsys.readouterr() assert out == u"0\t대한민국헌법 유구한 역사와\n9\t대한국민은 3·1운동으로 건립된 대한민국임시정부의 법통과 불의에\n98\t총강 제1조 ① 대한민국은 민주공화국이다. ②대한민국의\n100\t① 대한민국은 민주공화국이다. ②대한민국의 주권은 국민에게\n110\t나온다. 제2조 ① 대한민국의 국민이 되는\n126\t의무를 진다. 제3조 대한민국의 영토는 한반도와\n133\t부속도서로 한다. 제4조 대한민국은 통일을 지향하며,\n147\t추진한다. 제5조 ① 대한민국은 국제평화의 유지에\n787\t군무원이 아닌 국민은 대한민국의 영역안에서는 중대한\n1836\t파견 또는 외국군대의 대한민국 영역안에서의 주류에\n3620\t경제 제119조 ① 대한민국의 경제질서는 개인과\n"
def Stats(k) : #명사와 형용사의 값을 리턴함 noun_print = kolaw.open(k).read() sum = 0 for i in noun_print.splitlines(): value = i.split(":") sum=int(value[1])+sum return sum
def home(): if request.method == 'GET': text = kolaw.open('constitution.txt').read() stopwords = u'그,또는,한다' init = True else: text = request.form.get('wordtext', type=unicode) stopwords = request.form.get('stopwords', type=unicode) init = False minsyl = request.form.get('minsyl', 1, type=int) ntags = request.form.get('ntags', 10, type=int) tagger = request.form.get('tagger', '', type=unicode) posnv = request.form.get('noun', '', type=unicode)\ + request.form.get('verb', '', type=unicode) s = time.clock() tags = get_tags(text, minsyl, ntags, tagger, posnv, stopwords.split(',')) return render_template('home.html',\ init=init, text=text, tags=tags, time=time.clock()-s, textlen=len(text), stopwords=stopwords, ntags=len(tags))
def home(): if request.method=='GET': text = kolaw.open('constitution.txt').read() stopwords = u'그,또는,한다' init = True else: text = request.form.get('wordtext', type=unicode) stopwords = request.form.get('stopwords', type=unicode) init = False minsyl = request.form.get('minsyl', 1, type=int) ntags = request.form.get('ntags', 10, type=int) tagger = request.form.get('tagger', '', type=unicode) posnv = request.form.get('noun', '', type=unicode)\ + request.form.get('verb', '', type=unicode) s = time.clock() tags = get_tags(text, minsyl, ntags, tagger, posnv, stopwords.split(',')) return render_template('home.html',\ init=init, text=text, tags=tags, time=time.clock()-s, textlen=len(text), stopwords=stopwords, ntags=len(tags))
def extraction(self, f, p, original_file): global file file = f doc = kolaw.open(os.getcwd(), file).read().lower() doc = kolaw.open(file).read().lower() print("Start keyword extraction.") k = Komoran() pos = k.nouns(doc) cnt = Counter(pos) # format : nonus, frequency, path count = len(cnt) global data data = cnt.most_common(count) self.to_csv(p, original_file)
def test_corpus_kolaw(): from konlpy.corpus import kolaw fids = kolaw.fileids() kolaw.abspath() kolaw.abspath(fids[0]) assert kolaw.name == 'kolaw' assert kolaw.open('constitution.txt').read(10) ==\ u'\ub300\ud55c\ubbfc\uad6d\ud5cc\ubc95\n\n\uc720\uad6c'
def measure_time(taggers, mult=6): doc = kolaw.open('constitution.txt').read()*6 data = [[''] + taggers] for i in range(mult): doclen = 10**i times = [time()] diffs = [doclen] for tagger in taggers: r = tagging(tagger, doc[:doclen]) times.append(time()) diffs.append(times[-1] - times[-2]) print '%s\t%s\t%s' % (tagger[:5], doclen, diffs[-1]) pprint(r[:5]) data.append(diffs) print return data
def measure_time(taggers, mult=6): doc = kolaw.open('constitution.txt').read()*6 data = [['n'] + taggers] for i in range(mult): doclen = 10**i times = [time()] diffs = [doclen] for tagger in taggers: r = tagging(tagger, doc[:doclen]) times.append(time()) diffs.append(times[-1] - times[-2]) print ('%s\t%s\t%s' % (tagger[:5], doclen, diffs[-1])) pprint(r[:5]) data.append(diffs) print return data
def gen_cloud(): kkma = Kkma() # stopwords = set(STOPWORDS) # text = open("musical.txt","r").read() text = kolaw.open('constitution.txt').read() tokens_ko = kkma.nouns(unicode(text)) # tokens_ko = [each_word for each_word in tokens_ko if each_word not in stopwords] ko = nltk.Text(tokens_ko, name='musical review') data = ko.vocab().most_common(1000) tmp_data = dict(data) logo_coloring = Image.open("flipper_logo.png") np_logo_coloring = np.array(Image.open("flipper_logo.png")) mask = Image.new("RGB", logo_coloring.size, (255, 255, 255)) mask.paste(logo_coloring, logo_coloring) mask = np.array(mask) wc = WordCloud(font_path='/Library/Fonts/AppleGothic.ttf', relative_scaling=0.2, background_color="white", max_words=1000, mask=mask, min_font_size=10, max_font_size=500, random_state=42) wc.generate_from_frequencies(tmp_data) image_colors = ImageColorGenerator(np_logo_coloring) rc('font', family='AppleGothic') plt.rcParams['axes.unicode_minus'] = False plt.figure(figsize=(12, 12)) plt.imshow(wc.recolor(color_func=image_colors), interpolation='bilinear') plt.axis("off") plt.savefig('result.png') plt.show()
def measure_time(taggers, mult=6): doc = kolaw.open('constitution.txt').read() * 6 doc = doc.replace('\n', ' ') data = [['n', 'load'] + [10**i for i in range(mult)]] times = [time()] for tagger in taggers: diffs = [tagger.__name__] inst = tagger() inst.pos("가") times.append(time()) diffs.append(times[-1] - times[-2]) print('%s\t로딩\t%gs' % (tagger.__name__, diffs[-1])) for i in range(mult): doclen = 10**i r = inst.pos(doc[:doclen]) times.append(time()) diffs.append(times[-1] - times[-2]) print('%s\t%d\t%gs\t(Result Len: %d)' % (tagger.__name__, doclen, diffs[-1], len(r))) pprint(r[:5]) data.append(diffs) print() return data
max_words=1000, mask=mask).generate(fra) image_colors = ImageColorGenerator(mask) # color image를 기반으로 만든 컬러 = mask plt.figure(figsize=[7,7]) plt.imshow(wordcloud_usa.recolor(color_func=image_colors), interpolation="bilinear") plt.axis("off") plt.show() from konlpy.corpus import kolaw from konlpy.tag import Twitter t = Twitter() ko_con_text = kolaw.open('constitution.txt').read() print(type(ko_con_text)) ko_con_text[:100] tokens_ko = t.nouns(ko_con_text) tokens_ko[:10] stop_words = ['제', '월', '일', '조', '수', '때', '그', '이', '바', '및', '안'] tokens_ko = [each_word for each_word in tokens_ko if each_word not in stop_words] #stop_words는 set으로 만듭니다. ko = nltk.Text(tokens_ko, name="대한민국 헌법") ko.vocab().most_common(10) #데이터 타입 => 튜플리스트 #딕셔너리로 변환 (해야지 여기서 쓸 수 있음.) data = ko.vocab().most_common(500) tmp_data = dict(data)
import jpype def do_concurrent_tagging(start, end, lines, result): jpype.attachThreadToJVM() l = [k.pos(lines[i]) for i in range(start, end)] result.append(l) return if __name__ == "__main__": import time print('Number of lines in document:') k = Kkma() lines = kolaw.open('constitution.txt').read().splitlines() nlines = len(lines) print(nlines) print('Batch tagging:') s = time.clock() result = [] l = [k.pos(line) for line in lines] result.append(l) t = time.clock() print(t - s) print('Concurrent tagging:') result = [] t1 = Thread(target=do_concurrent_tagging, args=(0, int(nlines / 2), lines, result))
from konlpy.corpus import kolaw from threading import Thread import jpype def do_concurrent_tagging(start, end, lines, result): jpype.attachThreadToJVM() l = [k.pos(lines[i]) for i in range(start, end)] result.append(l) return if __name__=="__main__": import time print('Number of lines in document:') k = Kkma() lines = kolaw.open('constitution.txt').read().splitlines() nlines = len(lines) print(nlines) print('Batch tagging:') s = time.clock() result = [] l = [k.pos(line) for line in lines] result.append(l) t = time.clock() print(t - s) print('Concurrent tagging:') result = [] t1 = Thread(target=do_concurrent_tagging, args=(0, int(nlines/2), lines, result)) t2 = Thread(target=do_concurrent_tagging, args=(int(nlines/2), nlines, lines, result))
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)) print(embedding_model.most_similar(positive=tokenize('법률'), topn=50)) print(embedding_model.most_similar(positive=tokenize('결혼'), topn=50))
from nltk.corpus import gutenberg from nltk.tokenize import word_tokenize from konlpy.corpus import kolaw, kobill from nltk import Text from matplotlib import font_manager, rc import os, re from collections import defaultdict txtfilespath = "./0314_DownloadedNewstxts" # 긁어왔던 기사가 저장되어 있는 폴더 path = "C:/windows/fonts/HMKMRHD.ttf" # matplot의 폰트를 지정하기 위한 경로 설정 font = font_manager.FontProperties(fname=path).get_name() # 폰트매니저 객체 생성 rc("font", family=font) # 폰트 변경 # 지난시간 복습 (Korpus 길이 출력) kcorpus = kolaw.open(kolaw.fileids()[0]).read() ktokens = word_tokenize(kcorpus) # Korpus에 대해 토큰화 수행 print(len(ktokens), len(set(ktokens))) corpus = gutenberg.open(gutenberg.fileids()[0]).read() tokens = word_tokenize(corpus) # 토크나이즈 수행 print(len(tokens), len(set(tokens))) txt = Text(tokens) # 어휘 단위로 잘라줌. ktxt = Text(ktokens) # 어휘 단위로 잘라줌. # ------------------------------ 각 토큰에 어떤 단어가 몇번씩 나왔는지 분포 확인해보기. ------------------------------------------------- print( txt, txt.vocab() ) # <Text: Emma by Jane Austen 1816> <FreqDist with 8406 samples and 191785 outcomes> print(txt, txt.vocab().most_common()) # 가장 많이 나온 요소들을 표시 print(ktxt.vocab().most_common())
kkma.pos(txt) twitter.pos(txt) #konlpy의 corpus위치 정보 C:\Users\stu\Anaconda3\Lib\site-packages\konlpy\data\corpus ■ nltk 설치/실행: pip install nltk import nltk from konlpy.corpus import kolaw #kolaw 디렉토리에 있는 내용을 보여줌 kolaw.fileids() #파일 읽어 들이기 doc_ko = kolaw.open('constitution.txt').read() #twitter로 명사를 뽑아내고 별도의 변수에 저장 tokens_ko = twitter.nouns(doc_ko) tokens_ko # 단어의 수를 세기 -> dictonary형으로 자료형으로 만들어 없으면 새로운 방을 만들어 counting, 있으면 누적해서 counting # 단어의 수를 세기: nltk method 이용하기 ko = nltk.Text(tokens_ko) # token이 만들어짐 ko.tokens #단어개수를 뽑아줌 len(ko.tokens) #단어의 중복제거 len(set(ko.tokens)) #단어의 빈도수 ko.vocab()
from nltk.tokenize import sent_tokenize # 문장 단위 tokenize를 수행 from nltk.tokenize import word_tokenize, TweetTokenizer, regexp_tokenize # regexp_tokenize는 내가 정의한 정규식 표현으로 tokenizing을 수행함. from nltk.corpus import stopwords # 불용어 사전 # brown corpus : 만들어진지 30년이 지났지만 밸런스가 좋아서 교과서처럼 사용하는 Corpus. tagged corpus(어절분류 후 품사까지 붙어 있는)이다. # 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()
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)
from konlpy.corpus import kolaw fids = kolaw.fileids() fobj = kolaw.open(fids[0]) print(fobj.read(140))
db.query("set character_set_connection=utf8;") db.query("set character_set_server=utf8;") db.query("set character_set_client=utf8;") db.query("set character_set_results=utf8;") db.query("set character_set_database=utf8;") cursor.execute("set names utf8") #sql = "SELECT * FROM ( select * from Test3 limit 500 ) as A where A.Articlenumber = ArticleNumber order by rand() limit 100" #cursor.execute(sql.encode('utf8')) #rows = cursor.fetchall() document = '' koreanStopWord = kolaw.open('stopword.txt').readlines() document='' lenght=0 tokens_ko=[] Compound='' maxprobability =0 LDAkeyword=[] wd=[] wd2=[] wd3=[] sen=[] final=[] frequency=[] freword=[]
from konlpy.corpus import kolaw from konlpy.tag import Okt read_ = kolaw.open('constitution.txt').read() # [:20] print(read_) okt = Okt() # 형태소 단위로 나눈다. print(okt.morphs(read_, stem=True))
def main(argv): c = kolaw.open('C:\\dev_syhan\\aster_jeniel_test_dev_201808\\긍정어.txt').read() print(c[:100])
def get_klaw(): return kolaw.open(kolaw.fileids()[0]).read()
# -*- coding: utf-8 -*- """ Created on Fri Apr 24 11:02:26 2020 @author: USER """ # 꼬꼬마에 대하여 from konlpy.corpus import kolaw from konlpy.tag import Kkma from konlpy.utils import concordance #''' #헌법 관련된 텍스트 불러오기 contitution = kolaw.open('constitution.txt').read() print(contitution) # 몇 번째 줄에 '민주'라는 단어가 있는지 찾아줌 r = concordance(u'민주', contitution, show=False) print("show = False => ", r) # 텍스트 마이닝을 할 때 고려사항 : 정확성, 속도 from konlpy.tag import Kkma from konlpy.utils import pprint kkma = Kkma() text = u'네, 안녕하세요. 반갑습니다.'
def test_utils_concordance(): from konlpy.corpus import kolaw from konlpy.utils import concordance doc = kolaw.open('constitution.txt').read() ccd = concordance(u'대한민국', doc, show=True) assert ccd == [0, 9, 98, 100, 110, 126, 133, 147, 787, 1836, 3620]
wordcloud = WordCloud(background_color="white", max_words=2000, mask=alice_coloring, stopwords=stopwords, max_font_size=40, random_state=42) # generate word cloud wc = wordcloud.generate(text) image_colors = ImageColorGenerator(alice_coloring) # image_colors 반영 plt.figure(figsize=(8,8)) plt.imshow(wc.recolor(color_func=image_colors), interpolation='bilinear') plt.axis("off") plt.show() """ # Use Korean ko_con_text = kolaw.open('constitution.txt').read() # 출력 연습용 대한민국 헌법 tokens_ko = t.nouns(ko_con_text) # 텍스트를 단어별로 나눔(한글) stop_words = ['제', '월', '일', '조', '수', '때', '그', '이', '바', '및', '안'] # 금지 단어 수동 설정(완전히 같은 텍스트 출력하지 않음) tokens_ko = [ each_word for each_word in tokens_ko if each_word not in stop_words ] # stopword 적용 ko = nltk.Text(tokens_ko, name='대한민국 헌법') data = ko.vocab().most_common(500) # 카운트 해서 정렬까지 함 tmp_data = dict(data) korea_coloring = np.array(Image.open("WordCloudData/korea_mask.jpg")) image_colors = ImageColorGenerator(korea_coloring) wordcloud = WordCloud(
def main(): doc = kolaw.open('constitution.txt').read() lines = doc.split('\n')
if Stats('adjective.txt') >= 0 : print("빠름(형용사)") else : print("느림(형용사)") def Verb(): verb = konlpy.tag.Twitter().pos(readbook) grammar = """ VP : {<V.*>*} """ parser = nltk.RegexpParser(grammar).parse(verb) f = open('verb.txt','w') for subtree in parser.subtrees(): if subtree.label()=='VP': b = ' '.join((e[0] for e in list(subtree)))+':\n' f.writelines(b) f.close() print('사전완성(동사)') def __main__() : Noun() #명사 함수 Adjective() #형용사 함수 Verb() #동사 함수 inbook = input() t = time.time() #시간 readbook = kolaw.open(inbook).read() #파일 읽어오기 __main__() print('%.02f'%(time.time()-t)+'초 걸렸습니다.') #시간
len(t) txt = "텍스트 마이닝은 텍스트 형태의 데이터를 수학적 알고리즘에 기초하여 수집, 처리, 분석, 요약하는 연구기법을 통칭하는 용어이다." kkma.nouns(txt) ### 이 경우에는 Kkma()가 더 분석 잘 했음! twitter.nouns(txt) # 3) nltk 패키지 ## Twitter()나 Kkma()로 추출해낸 명사들의 "빈도 수" 파악! ## C:\Users\stu\Anaconda3\Lib\site-packages\konlpy\data\corpus\kolaw ## pip install nltk import nltk from konlpy.corpus import kolaw kolaw.fileids() ### 파일 리스트 정보 확인 가능 ## 파일 오픈 doc_ko = kolaw.open('constitution.txt').read() tokens_ko = twitter.nouns(doc_ko) tokens_ko ## nltk에 속한 메소드들 확인 ko = nltk.Text(tokens_ko) ### 분석해야 할 토큰 분석 ko.tokens ### 만들어진 토큰들 확인 len(ko.tokens) ### 전체 토큰 수 len(set(ko.tokens)) ### 중복 제거 후의 토큰 수 ko.vocab() ### 빈도 수 체크 ko.vocab().most_common(10) ### 상위 10개만 뽑아냄 import matplotlib.pyplot as plt from matplotlib import font_manager, rc font_name = font_manager.FontProperties( fname='c:/Windows/Fonts/malgun.ttf').get_name()
from konlpy.tag import Kkma from konlpy.corpus import kolaw from konlpy.utils import pprint from nltk import collocations kolaw.fileids() measures = collocations.BigramAssocMeasures() doc = kolaw.open('./test2.txt').read() print(doc) # print('\nCollocations among tagged words:') # tagged_words = Kkma().pos(doc) # finder = collocations.BigramCollocationFinder.from_words(tagged_words) # pprint(finder.nbest(measures.pmi, 10)) # top 5 n-grams with highest PMI # print('\nCollocations among words:') # words = [w for w, t in tagged_words] # ignored_words = [u'안녕'] # finder = collocations.BigramCollocationFinder.from_words(words) # finder.apply_word_filter(lambda w: len(w) < 2 or w in ignored_words) # finder.apply_freq_filter(3) # only bigrams that appear 3+ times # pprint(finder.nbest(measures.pmi, 10)) # print('\nCollocations among tags:') # tags = [t for w, t in tagged_words] # finder = collocations.BigramCollocationFinder.from_words(tags) # pprint(finder.nbest(measures.pmi, 5))
import numpy as np import pandas as pd import os import matplotlib.pyplot as plt import seaborn as sns import konlpy from konlpy.corpus import kolaw print(kolaw.open('constitution.txt').read()[:20])
# 기본 실행 코드 #%% #법률 말뭉치(대한민국 헌법) from konlpy.corpus import kolaw c = kolaw.open('constitution.txt').read() #print(c[:1000]) #wordcloud 시각화 전 빈도분석 실시 from konlpy.corpus import kolaw data = kolaw.open('constitution.txt').read() from konlpy.tag import Komoran komoran = Komoran() #print(komoran.nouns("%r"%data[0:1000])) #명사들을 공백으로 처리 word_list = komoran.nouns("%r"%data[0:1000]) text = ' '.join(word_list) #print(text) #wordcloud 시각화 import matplotlib.pyplot as plt %matplotlib inline from wordcloud import WordCloud wordc = WordCloud() wordc.generate(text) # 각자 실행 가능한 코드(Jupyter Notebook 적용) #%% #wordcloud graph 그리기 (한글 깨짐 현상 발생) plt.figure()