단어 구름을 그리기 위해 wordcloud
를 설치한다.
!pip install wordcloud
단어 빈도표를 사전(dict
) 형식으로 변경한다.
count_dic = dict(zip(word_count.단어, word_count.빈도))
from wordcloud import WordCloud
한글을 단어 구름에 그리기 위해 글꼴이 필요하다. 기본으로 설치된 한글 글꼴을 사용해도 되지만 여기서는 나눔글꼴을 사용하려고 한다. 윈도나 맥에서는 네이버 나눔글꼴 홈페이지에 접속하여 다운로드 받아 설치한다. colab에서는 아래 명령어로 설치할 수 있다.
!apt install fonts-nanum
나눔글꼴의 종류를 확인한다.
!ls /usr/share/fonts/truetype/nanum/
NanumBarunGothicBold.ttf NanumMyeongjoBold.ttf NanumSquareRoundR.ttf NanumBarunGothic.ttf NanumMyeongjo.ttf NanumSquareR.ttf NanumGothicBold.ttf NanumSquareB.ttf NanumGothic.ttf NanumSquareRoundB.ttf
단어 구름을 그릴 때, 글꼴의 위치를 설정해주어야 한다. 윈도나 맥의 경우 font_path
를 아래와 같이 설정한다.
C:/Windows/Fonts/NanumGothic.ttf
/Library/Fonts/NanumGothic.otf
윈도의 경우, NanumGothic.ttf
대신 기본 설치된 Malgun.ttf
을 사용해도 된다.
wc = WordCloud(
font_path='/usr/share/fonts/truetype/nanum/NanumGothic.ttf',
background_color='white',
max_words=100,
width=400,
height=300)
단어 빈도의 사전을 단어 구름으로 변환한다.
cloud = wc.fit_words(count_dic)
그림을 출력한다.
cloud.to_image()
그림 파일을 저장한다.
cloud.to_file('cloud.png')
<wordcloud.wordcloud.WordCloud at 0x7f8e82396610>