안녕하세요. @anpigon 입니다.
이전 글에 이어서 이번에는 스팀잇에 작성한 글에서 단어를 추출하여 단어구름 을 만들어 보겠습니다.
이전글 워드클라우드 모듈 설치워드클라우드(wordcloud) 모듈을 설치한다.
pip install wordcloud
워드클라우드 깃허브에서 사용방법 또는 예제 소스를 참고할 수 있다.
스팀잇에 작성한 글 가져오기
스팀잇에서 내가 작성한 글을 가져온다. 작성한 글을 모두 가져오려면 오래 걸리니 우선 1건만 가져와서 테스트해본다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 from steem import Steem from steem.blog import Blogusername = 'anpigon' b = Blog(username) posts = b.take(1 ) texts = [] for post in posts: if post.body != "" : texts.append(post.body.replace('\n' , '' )) print (texts)
결과 화면
형태소 분석으로 단어 추출
형태소 분석에는 은전한닢(Mecab) 분석기를 사용한다. 분석기 중에서 은전한닢이 가장 속도가 빠르고 분석결과가 만족스러웠다.
1 2 3 4 5 6 7 from konlpy.tag import Mecabtagger = Mecab() tokens = [] for text in texts: tokens += tagger.nouns(text) print (tokens)
결과 화면
단어구름 만들기
이제 스팀잇 글에서 뽑아낸 단어를 가지고 단어구름을 만들어 보자.
1 2 3 4 5 6 7 import matplotlib.pyplot as pltfrom wordcloud import WordCloudwordcloud = WordCloud().generate(' ' .join(tokens)) plt.imshow(wordcloud, interpolation='bilinear' ) plt.axis("off" ) plt.show()
결과 화면
위와 같은 이미지가 나타난다. wordcloud가 한글 폰트를 지원하지 않아서 그렇다.
한글 폰트가 설치된 경로를 설정한다. 폰트가 설치된 경로는 OS마다 다르기 때문에 이 부분은 각자 확인하고 설정해야한다. 그리고 흰색 배경이 좋아서 배경색을 흰색으로 변경하였다.
1 2 3 4 5 6 7 8 9 10 wordcloud = WordCloud( font_path='/Library/Fonts/AppleGothic.ttf' , background_color='white' ).generate(' ' .join(tokens)) plt.imshow(wordcloud, interpolation='bilinear' ) plt.axis("off" ) plt.show()
결과 화면
스팀잇에서 작성한 모든글을 가져와서 단어구름 만들기
글 한건에 대해서 분석이 완료 되었다. 이제 내가 작성한 모든 글을 가져와서 분석해보자.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 from steem import Steem from steem.blog import Blogimport matplotlib.pyplot as pltfrom wordcloud import WordCloudfrom konlpy.tag import Mecabusername = 'anpigon' b = Blog(username) posts = b.all () texts = [] for post in posts: if post.body != "" : texts.append(post.body.replace('\n' , '' )) tagger = Mecab() tokens = [] for text in texts: tokens += tagger.nouns(text) wordcloud = WordCloud( font_path='/Library/Fonts/AppleGothic.ttf' , background_color='white' , max_words=2000 , ).generate(' ' .join(tokens)) plt.imshow(wordcloud, interpolation='bilinear' ) plt.axis("off" ) plt.show()
결과 화면
내가 평소에 글을 작성할 때, 구현 , 사용 , 아래 단어를 많이 사용하는 것을 볼 수 있다. 해당 단어는 카운트에서 제외하고 다시 실행해보자.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 from wordcloud import WordCloud, STOPWORDSstopwords = set (STOPWORDS) stopwords.add("사용" ) stopwords.add("구현" ) stopwords.add("아래" ) wordcloud = WordCloud( font_path='/Library/Fonts/AppleGothic.ttf' , stopwords=stopwords, background_color='white' , max_words=2000 , ).generate(' ' .join(tokens)) plt.imshow(wordcloud, interpolation='bilinear' ) plt.axis("off" ) plt.show()
결과 화면
아까와는 다른 결과가 나왔다. 이제 사각형 형태의 단어구름 모양을 이쁜 구름모양 ☁으로 바꿔보자.
참고로, 워드클라우드 깃허브 샘플소스에는 엘리스와 다스베이더 예제가 포함되어 있다.
나는 픽사베이(pixabay)에서 무료 구름 이미지 를 가져와서 적용하였다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 from os import pathfrom PIL import Imageimport numpy as npimport osd = path.dirname(__file__) if "__file__" in locals () else os.getcwd() mask = np.array(Image.open (path.join(d, 'cloud.png' ))) wordcloud = WordCloud( font_path='/Library/Fonts/AppleGothic.ttf' , background_color="white" , max_words=2000 , stopwords=stopwords, mask=mask, ).generate(' ' .join(tokens)) plt.imshow(wordcloud, interpolation='bilinear' ) plt.axis("off" ) plt.show()
결과 화면
이미지 파일로 저장하고 싶으면 to_file()
함수를 사용하면 된다.
1 wordcloud.to _file(path .join (d , "wordcloud.png" ) )
단어 빈도수 계산
nltk와 plt모듈을 사용하면 단어 빈도수를 계산하여 그래프로 나타낼 수 있다.
1 2 3 4 5 6 import nltkplt.figure(figsize=(12 ,6 )) words = nltk.Text(tokens, name='단어 빈도수' ) words.plot(50 ) plt.show()
결과 화면
여기까지 읽어주셔서 감사합니다.