프로그래밍/데이터사이언스

앨리스 워드클라우드

카멜필름 2022. 3. 25. 23:30

#pip install konlpy 한글을 사용하기 위해 세종사전을 이용 세종사전이 세팅되지 않을 때는 JAVAjdk를 설치해야 함 pip install wordcloud

In [2]:
 

 
import nltk
nltk.download('gutenberg')
#파일 다운 앨리스 책 가져옴
from nltk.corpus import gutenberg
file_names = gutenberg.fileids() #파일 제목을 읽어온다.
print(file_names)
 
executed in 4.32s, finished 17:44:00 2021-10-04
['austen-emma.txt', 'austen-persuasion.txt', 'austen-sense.txt', 'bible-kjv.txt', 'blake-poems.txt', 'bryant-stories.txt', 'burgess-busterbrown.txt', 'carroll-alice.txt', 'chesterton-ball.txt', 'chesterton-brown.txt', 'chesterton-thursday.txt', 'edgeworth-parents.txt', 'melville-moby_dick.txt', 'milton-paradise.txt', 'shakespeare-caesar.txt', 'shakespeare-hamlet.txt', 'shakespeare-macbeth.txt', 'whitman-leaves.txt']
[nltk_data] Downloading package gutenberg to
[nltk_data]     C:\Users\유진아\AppData\Roaming\nltk_data...
[nltk_data]   Package gutenberg is already up-to-date!
In [3]:
 

 
nltk.download('punkt')
nltk.download('wordnet')
nltk.download('stopwords')
 
executed in 183ms, finished 17:44:00 2021-10-04
[nltk_data] Downloading package punkt to
[nltk_data]     C:\Users\유진아\AppData\Roaming\nltk_data...
[nltk_data]   Package punkt is already up-to-date!
[nltk_data] Downloading package wordnet to
[nltk_data]     C:\Users\유진아\AppData\Roaming\nltk_data...
[nltk_data]   Package wordnet is already up-to-date!
[nltk_data] Downloading package stopwords to
[nltk_data]     C:\Users\유진아\AppData\Roaming\nltk_data...
[nltk_data]   Package stopwords is already up-to-date!
Out[3]:
True
In [4]:
 

 
doc_alice = gutenberg.open('carroll-alice.txt').read()
print('#Num of characters used:', len(doc_alice)) #사용된 문자의 수
print('#Text sample:')
print(doc_alice[:500]) #앞의 500자만 출력
 
executed in 11ms, finished 17:44:00 2021-10-04
#Num of characters used: 144395
#Text sample:
[Alice's Adventures in Wonderland by Lewis Carroll 1865]

CHAPTER I. Down the Rabbit-Hole

Alice was beginning to get very tired of sitting by her sister on the
bank, and of having nothing to do: once or twice she had peeped into the
book her sister was reading, but it had no pictures or conversations in
it, 'and what is the use of a book,' thought Alice 'without pictures or
conversation?'

So she was considering in her own mind (as well as she could, for the
hot day made her feel very sleepy an
In [5]:
 

 
from nltk.tokenize import word_tokenize
tokens_alice = word_tokenize(doc_alice) #토큰화 실행
print('#Num of tokens used:', len(tokens_alice))
print('#Token sample:')
print(tokens_alice[:20])
#구두점이나 대괄호 빼는 방법 생각해내기
#단어는 최소 의미. 같은 의미 가진 애들 같다고 보고 싶음, 문법상 달라서 문제
#그래서 스테밍을 함
#같은 의미 가진 애들은 같게 봐꿔줌-포터스테머-규칙을 찾음 속도 빠름, 예외 많음
#wordNEtLemmatizer: 사전을 찾아서 속도 느림 . 정확도 높음. 품사를 알아야 함.
# 이 과정을 정규화라고 함
 
executed in 681ms, finished 17:44:01 2021-10-04
#Num of tokens used: 33493
#Token sample:
['[', 'Alice', "'s", 'Adventures', 'in', 'Wonderland', 'by', 'Lewis', 'Carroll', '1865', ']', 'CHAPTER', 'I', '.', 'Down', 'the', 'Rabbit-Hole', 'Alice', 'was', 'beginning']
In [6]:
 

 
from nltk.stem import PorterStemmer
stemmer = PorterStemmer()
stem_tokens_alice = [stemmer.stem(token) for token in tokens_alice] #모든 토큰에 대해 스테밍 실행
print('#Num of tokens after stemming:', len(stem_tokens_alice))
print('#Token sample:')
print(stem_tokens_alice[:20])
 
executed in 1.52s, finished 17:44:02 2021-10-04
#Num of tokens after stemming: 33493
#Token sample:
['[', 'alic', "'s", 'adventur', 'in', 'wonderland', 'by', 'lewi', 'carrol', '1865', ']', 'chapter', 'i', '.', 'down', 'the', 'rabbit-hol', 'alic', 'wa', 'begin']

분석할 때 빼고 싶은 단어 거르기 분석 대상 아닌 단어들 처리

In [7]:
 

 
from nltk.stem import WordNetLemmatizer
lemmatizer = WordNetLemmatizer()
lem_tokens_alice = [lemmatizer.lemmatize(token) for token in tokens_alice] #모든 토큰에 대해 스테밍 실행
print('#Num of tokens after lemmatization:', len(lem_tokens_alice))
print('#Token sample:')
print(lem_tokens_alice[:20])
 
executed in 4.76s, finished 17:44:07 2021-10-04
#Num of tokens after lemmatization: 33493
#Token sample:
['[', 'Alice', "'s", 'Adventures', 'in', 'Wonderland', 'by', 'Lewis', 'Carroll', '1865', ']', 'CHAPTER', 'I', '.', 'Down', 'the', 'Rabbit-Hole', 'Alice', 'wa', 'beginning']
In [8]:
 

 
from nltk.tokenize import RegexpTokenizer
tokenizer = RegexpTokenizer("[\w']{3,}") 
reg_tokens_alice = tokenizer.tokenize(doc_alice.lower())
print('#Num of tokens with RegexpTokenizer:', len(reg_tokens_alice))
print('#Token sample:')
print(reg_tokens_alice[:20])
 
executed in 26ms, finished 17:44:07 2021-10-04
#Num of tokens with RegexpTokenizer: 21616
#Token sample:
["alice's", 'adventures', 'wonderland', 'lewis', 'carroll', '1865', 'chapter', 'down', 'the', 'rabbit', 'hole', 'alice', 'was', 'beginning', 'get', 'very', 'tired', 'sitting', 'her', 'sister']
In [9]:
 

 
from nltk.corpus import stopwords #일반적으로 분석대상이 아닌 단어들
english_stops = set(stopwords.words('english')) #반복이 되지 않도록 set으로 변환
result_alice = [word for word in reg_tokens_alice if word not in english_stops] #stopwords를 제외한 단어들만으로 list를 생성
print('#Num of tokens after stopword elimination:', len(result_alice))
print('#Token sample:')
print(result_alice[:20])
 
executed in 26ms, finished 17:44:07 2021-10-04
#Num of tokens after stopword elimination: 12999
#Token sample:
["alice's", 'adventures', 'wonderland', 'lewis', 'carroll', '1865', 'chapter', 'rabbit', 'hole', 'alice', 'beginning', 'get', 'tired', 'sitting', 'sister', 'bank', 'nothing', 'twice', 'peeped', 'book']

여기까지가 전처리 최소의미 단위로 되어있다고 가정

In [10]:
 
 

 
alice_word_count = dict() #딕셔너리 생성
 
for word in result_alice: #단어들에 대해 개수를 셈. get함수 단어의 개수를 불러와서 인식해야 하는데 한 번도 없는 단어 나오면 오류 나와서 없는 단어엔 0 추가
    alice_word_count[word] = alice_word_count.get(word, 0) + 1
print('#Num of used words:', len(alice_word_count))
sorted_word_count = sorted(alice_word_count, key=alice_word_count.get, reverse=True)
print("#Top 20 high frequency words:")
 
for key in sorted_word_count[:20]: #빈도수 상위 20개의 단어를 출력
    print(f'{repr(key)}: {alice_word_count[key]}', end=', ')
 
executed in 41ms, finished 17:44:07 2021-10-04
#Num of used words: 2687
#Top 20 high frequency words:
'said': 462, 'alice': 385, 'little': 128, 'one': 98, 'know': 88, 'like': 85, 'went': 83, 'would': 78, 'could': 77, 'thought': 74, 'time': 71, 'queen': 68, 'see': 67, 'king': 61, 'began': 58, 'turtle': 57, "'and": 56, 'way': 56, 'mock': 56, 'quite': 55, 
In [11]:
 

 
alice_word_count = dict()
 
for word in result_alice:
    alice_word_count[word] = alice_word_count.get(word, 0) + 1
print('#Num of used words:', len(alice_word_count))
sorted_word_count = sorted(alice_word_count, key=alice_word_count.get, reverse=True)
print("#Top 20 high frequency words:")
 
for key in sorted_word_count[:20]: #빈도수 상위 20개의 단어를 출력
    print(f'{repr(key)}: {alice_word_count[key]}', end=', ')
 
executed in 38ms, finished 17:44:07 2021-10-04
#Num of used words: 2687
#Top 20 high frequency words:
'said': 462, 'alice': 385, 'little': 128, 'one': 98, 'know': 88, 'like': 85, 'went': 83, 'would': 78, 'could': 77, 'thought': 74, 'time': 71, 'queen': 68, 'see': 67, 'king': 61, 'began': 58, 'turtle': 57, "'and": 56, 'way': 56, 'mock': 56, 'quite': 55, 
In [12]:
 

 
import matplotlib.pyplot as plt
%matplotlib inline
w = [alice_word_count[key] for key in sorted_word_count] #정렬된 단어 리스트에 대해 빈도수를 가져와서 리스트 생성
plt.plot(w)
plt.show()
 
executed in 1.20s, finished 17:44:08 2021-10-04

너무 많고 단어인지 안 보임. 앞에거에 빈도 집중됨. 이걸 지플의 법칙이라고 함 빈도수 너무 높은 단 어 쓸모 없겠다-->다른 이야기

In [13]:
 

 
n = sorted_word_count[:20] #빈도수 상위 20개의 단어만 추출
w = [alice_word_count[key] for key in n] #추출된 단어에 대해 빈도를 추출
plt.bar(range(len(n)),w,tick_label=n) #막대그래프를 그림
plt.show()
 
executed in 667ms, finished 17:44:09 2021-10-04
In [14]:
 

 
n = sorted_word_count[:20][::-1] #빈도수 상위 20개의 단어를 추출하여 역순으로 정렬
w = [alice_word_count[key] for key in n] #얘는 맞게 가져와서 뒤집을 필요x
plt.barh(range(len(n)),w,tick_label=n) #수평 막대그래프
plt.show()
 
executed in 573ms, finished 17:44:09 2021-10-04
In [15]:
 

 
!pip install wordcloud
 
executed in 2.52s, finished 17:44:12 2021-10-04
Requirement already satisfied: wordcloud in c:\programdata\anaconda3\lib\site-packages (1.8.1)
Requirement already satisfied: numpy>=1.6.1 in c:\programdata\anaconda3\lib\site-packages (from wordcloud) (1.20.1)
Requirement already satisfied: matplotlib in c:\programdata\anaconda3\lib\site-packages (from wordcloud) (3.3.4)
Requirement already satisfied: pillow in c:\programdata\anaconda3\lib\site-packages (from wordcloud) (8.2.0)
Requirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.3 in c:\programdata\anaconda3\lib\site-packages (from matplotlib->wordcloud) (2.4.7)
Requirement already satisfied: kiwisolver>=1.0.1 in c:\programdata\anaconda3\lib\site-packages (from matplotlib->wordcloud) (1.3.1)
Requirement already satisfied: cycler>=0.10 in c:\programdata\anaconda3\lib\site-packages (from matplotlib->wordcloud) (0.10.0)
Requirement already satisfied: python-dateutil>=2.1 in c:\programdata\anaconda3\lib\site-packages (from matplotlib->wordcloud) (2.8.1)
Requirement already satisfied: six in c:\programdata\anaconda3\lib\site-packages (from cycler>=0.10->matplotlib->wordcloud) (1.15.0)
WARNING: Ignoring invalid distribution - (c:\programdata\anaconda3\lib\site-packages)
WARNING: Ignoring invalid distribution -eautifulsoup4 (c:\programdata\anaconda3\lib\site-packages)
WARNING: Ignoring invalid distribution - (c:\programdata\anaconda3\lib\site-packages)
WARNING: Ignoring invalid distribution -eautifulsoup4 (c:\programdata\anaconda3\lib\site-packages)
WARNING: Ignoring invalid distribution - (c:\programdata\anaconda3\lib\site-packages)
WARNING: Ignoring invalid distribution -eautifulsoup4 (c:\programdata\anaconda3\lib\site-packages)
WARNING: Ignoring invalid distribution - (c:\programdata\anaconda3\lib\site-packages)
WARNING: Ignoring invalid distribution -eautifulsoup4 (c:\programdata\anaconda3\lib\site-packages)
WARNING: Ignoring invalid distribution - (c:\programdata\anaconda3\lib\site-packages)
WARNING: Ignoring invalid distribution -eautifulsoup4 (c:\programdata\anaconda3\lib\site-packages)
In [25]:
 

 
from wordcloud import WordCloud
# Generate a word cloud image
wordcloud = WordCloud().generate(doc_alice) #전처리 안 하고 원본 그대로 사용
plt.axis("off")
plt.imshow(wordcloud, interpolation='bilinear') #이미지를 출력
plt.show()
 
executed in 3.28s, finished 20:52:49 2021-10-04
In [17]:
 

 
wordcloud.to_array().shape
 
executed in 608ms, finished 17:44:15 2021-10-04
Out[17]:
(200, 400, 3)
In [18]:
 

 
wordcloud = WordCloud(max_font_size=60).generate_from_frequencies(alice_word_count)
plt.figure()
plt.axis("off") #그래프 축 뺌
plt.imshow(wordcloud, interpolation="bilinear")
plt.show()
 
executed in 1.82s, finished 17:44:17 2021-10-04
In [23]:
 

 
wordcloud = WordCloud(max_font_size=60, width=600, height=300)
wordcloud.generate_from_frequencies(alice_word_count)
plt.figure()
plt.axis("off") #그래프 축 뺌
plt.imshow(wordcloud, interpolation="bilinear")
plt.show()
#그림은 두번째 있는 게 더 큼
#아이엠 쇼가 이미지를 줄여서 보여줌
#여기서 저장하면 줄여 만든 이미지가 저장됨
#저장된 이미지를 사용해야지 아이엠쇼를 써서 저장하면 안 됨
 
executed in 2.12s, finished 18:51:20 2021-10-04
In [27]:
 

 
import numpy as np
from PIL import Image
alice_mask = np.array(Image.open("alice_mask.png")) # 배경이미지를 불러와서 numpy array로 변환
 
wc = WordCloud(background_color="white", # 배경색 지정
               max_words=30, # 출력할 최대 단어 수
               mask=alice_mask, # 배경으로 사용할 이미지
               contour_width=3,  # 테두리선의 크기
               contour_color='steelblue') # 테두리선의 색
wc.generate_from_frequencies(alice_word_count) # 워드 클라우드 생성
wc.to_file("alice.png") # 결과를 이미지 파일로 저장
# 화면에 결과를 출력
plt.figure()
plt.axis("off")
plt.imshow(wc, interpolation='bilinear')
plt.show()
#아이엠 쇼 원래 이미지 크기대로 출력해주지 않음. 이 경우에 그려놓고 하면 
 
executed in 2.32s, finished 21:01:48 2021-10-04
In [20]:
 

 
pip install konlpy
 
executed in 2.48s, finished 17:44:21 2021-10-04
Requirement already satisfied: konlpy in c:\programdata\anaconda3\lib\site-packages (0.5.2)Note: you may need to restart the kernel to use updated packages.
Requirement already satisfied: beautifulsoup4==4.6.0 in c:\programdata\anaconda3\lib\site-packages (from konlpy) (4.6.0)
Requirement already satisfied: tweepy>=3.7.0 in c:\programdata\anaconda3\lib\site-packages (from konlpy) (4.0.1)
Requirement already satisfied: colorama in c:\programdata\anaconda3\lib\site-packages (from konlpy) (0.4.4)
Requirement already satisfied: lxml>=4.1.0 in c:\programdata\anaconda3\lib\site-packages (from konlpy) (4.6.3)
Requirement already satisfied: numpy>=1.6 in c:\programdata\anaconda3\lib\site-packages (from konlpy) (1.20.1)
Requirement already satisfied: JPype1>=0.7.0 in c:\programdata\anaconda3\lib\site-packages (from konlpy) (1.3.0)
Requirement already satisfied: requests-oauthlib<2,>=1.0.0 in c:\programdata\anaconda3\lib\site-packages (from tweepy>=3.7.0->konlpy) (1.3.0)
Requirement already satisfied: requests<3,>=2.11.1 in c:\programdata\anaconda3\lib\site-packages (from tweepy>=3.7.0->konlpy) (2.25.1)
Requirement already satisfied: certifi>=2017.4.17 in c:\programdata\anaconda3\lib\site-packages (from requests<3,>=2.11.1->tweepy>=3.7.0->konlpy) (2020.12.5)
Requirement already satisfied: urllib3<1.27,>=1.21.1 in c:\programdata\anaconda3\lib\site-packages (from requests<3,>=2.11.1->tweepy>=3.7.0->konlpy) (1.26.4)
Requirement already satisfied: chardet<5,>=3.0.2 in c:\programdata\anaconda3\lib\site-packages (from requests<3,>=2.11.1->tweepy>=3.7.0->konlpy) (4.0.0)
Requirement already satisfied: idna<3,>=2.5 in c:\programdata\anaconda3\lib\site-packages (from requests<3,>=2.11.1->tweepy>=3.7.0->konlpy) (2.10)
Requirement already satisfied: oauthlib>=3.0.0 in c:\programdata\anaconda3\lib\site-packages (from requests-oauthlib<2,>=1.0.0->tweepy>=3.7.0->konlpy) (3.1.1)

WARNING: Ignoring invalid distribution - (c:\programdata\anaconda3\lib\site-packages)
WARNING: Ignoring invalid distribution -eautifulsoup4 (c:\programdata\anaconda3\lib\site-packages)
WARNING: Ignoring invalid distribution - (c:\programdata\anaconda3\lib\site-packages)
WARNING: Ignoring invalid distribution -eautifulsoup4 (c:\programdata\anaconda3\lib\site-packages)
WARNING: Ignoring invalid distribution - (c:\programdata\anaconda3\lib\site-packages)
WARNING: Ignoring invalid distribution -eautifulsoup4 (c:\programdata\anaconda3\lib\site-packages)
WARNING: Ignoring invalid distribution - (c:\programdata\anaconda3\lib\site-packages)
WARNING: Ignoring invalid distribution -eautifulsoup4 (c:\programdata\anaconda3\lib\site-packages)
WARNING: Ignoring invalid distribution - (c:\programdata\anaconda3\lib\site-packages)
WARNING: Ignoring invalid distribution -eautifulsoup4 (c:\programdata\anaconda3\lib\site-packages)
In [21]:
 

 
from konlpy.corpus import kolaw
const_doc = kolaw.open('constitution.txt').read()
print(type(const_doc)) #가져온 데이터의 type을 확인
print(len(const_doc))
print(const_doc[:600])
 
executed in 10ms, finished 17:44:21 2021-10-04
<class 'str'>
18884
대한민국헌법

유구한 역사와 전통에 빛나는 우리 대한국민은 3·1운동으로 건립된 대한민국임시정부의 법통과 불의에 항거한 4·19민주이념을 계승하고, 조국의 민주개혁과 평화적 통일의 사명에 입각하여 정의·인도와 동포애로써 민족의 단결을 공고히 하고, 모든 사회적 폐습과 불의를 타파하며, 자율과 조화를 바탕으로 자유민주적 기본질서를 더욱 확고히 하여 정치·경제·사회·문화의 모든 영역에 있어서 각인의 기회를 균등히 하고, 능력을 최고도로 발휘하게 하며, 자유와 권리에 따르는 책임과 의무를 완수하게 하여, 안으로는 국민생활의 균등한 향상을 기하고 밖으로는 항구적인 세계평화와 인류공영에 이바지함으로써 우리들과 우리들의 자손의 안전과 자유와 행복을 영원히 확보할 것을 다짐하면서 1948년 7월 12일에 제정되고 8차에 걸쳐 개정된 헌법을 이제 국회의 의결을 거쳐 국민투표에 의하여 개정한다.

       제1장 총강
  제1조 ① 대한민국은 민주공화국이다.
②대한민국의 주권은 국민에게 있고, 모든 권력은 국민으로부터 나온다.
  제2조 ① 대한민국의 국민이 되는 요건은 법률로 정한다.
②국가는 법률이 정하는 바에 의하여 재외국민을 보호할 의무를 진다.
  제3조 대한민
In [22]:
 

 
from konlpy.tag import Okt
t = Okt()
tokens_const = t.morphs(const_doc) #형태소 단위로 tokenize
print('#토큰의 수:', len(tokens_const))
print('#앞 100개의 토큰')
print(tokens_const[:100])
 
executed in 641ms, finished 17:45:41 2021-10-04
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-22-5e320f8c4552> in <module>
----> 1 from konlpy.tag import Okt
      2 t = Okt()
      3 tokens_const = t.morphs(const_doc) #형태소 단위로 tokenize
      4 
      5 print('#토큰의 수:', len(tokens_const))

C:\ProgramData\Anaconda3\lib\site-packages\konlpy\__init__.py in <module>
     10 
     11 from konlpy.jvm import init_jvm
---> 12 from konlpy import (
     13     corpus,
     14     data,

C:\ProgramData\Anaconda3\lib\site-packages\konlpy\stream\__init__.py in <module>
      6 
      7 from konlpy.stream.base import BaseStreamer, KonlpyStreamerError
----> 8 from konlpy.stream.twitter import TwitterStreamer
      9 from konlpy.stream.naver import NaverStreamer
     10 from konlpy.stream.dcinside import DCInsideStreamer

C:\ProgramData\Anaconda3\lib\site-packages\konlpy\stream\twitter.py in <module>
     15 
     16 
---> 17 class CorpusListener(tweepy.StreamListener):
     18     def __init__(self, options, dirname, word_list):
     19         """CorpusListener is a tweepy listener to listen on filtered list of words.

AttributeError: module 'tweepy' has no attribute 'StreamListener'

In [ ]:
 

 
728x90
LIST