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'
from konlpy.corpus import kolaw kolaw.fileids() c = kolaw.open('constitution.txt').read() print(c[:40])
import nltk nltk.download("punkt") # 구두점 정의에 필요한 모듈. (※ 다운로드는 최초 1회만 하면 됨) from nltk.corpus import brown, gutenberg 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()
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())
def get_klaw(): return kolaw.open(kolaw.fileids()[0]).read()
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))
import pandas as pd import matplotlib.pyplot as plt from konlpy.corpus import kolaw print(kolaw.fileids()) c = kolaw.open('constitution.txt').read() print(c[:40]) from konlpy.corpus import kobill kobill.fileids() d = kobill.open('1809890.txt').read() print(d[:40]) from konlpy.tag import * hannanum = Hannanum() kkma = Kkma() komoran = Komoran() ##mecab = Mecab() okt = Okt() hannanum.nouns(c[:40]) kkma.nouns(c[:40]) # komoran은 빈줄이 있으면 에러가 남 komoran.nouns("\n".join([s for s in c[:40].split("\n") if s])) ##mecab.nouns(c[:40]) okt.nouns(c[:40])
from konlpy.corpus import kolaw fids = kolaw.fileids() fobj = kolaw.open(fids[0]) print(fobj.read(140))
t = twitter.nouns(txt) ### Kkma()로 분석할 때와 결과가 다름! len(k) 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 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])