자연어처리

파이썬으로 워드 클라우드(Word Cloud) 만들기

zzheng 2024. 5. 22. 01:28

 

워드 클라우드(Word Cloud)

: 워드 클라우드는 단어들을 분석해 중요도 빈도수 인기도 등을 고려해 단어들을 시각화한 방법을 말한다. 



그럼 파이썬을 이용해서 워드 클라우드 분석을 해보겠습니다.

먼저, 워드 클라우드를 하기 위해서는 설치가 필요합니다. 

!pip install wordcloud

 

다음으로, 예쁘게 워드 클라우드를 만들기 위해 폰트와 배경 그림을 다운했습니다. 

워드 클라우드 mask 옵션을 이용하면, 다른 모양의 워드 클라우드를 생성할 수 있습니다.

따로 지정하지 않을경우, 네모난 모양으로 출력됩니다. 

 

저는 동그라미 배경과 NotoSansKR-Medium 폰트를 사용했습니다. 

또한, 예쁜 색상을 위해 seaborn을 이용해서 색상을 지정했습니다.

import random
import seaborn as sns

mecab = Mecab()

all_reviews = ' '.join(df['Advantage']) #데이터입력

nouns = mecab.nouns(all_reviews)

word_counts = Counter(nouns)
top_words = word_counts.most_common(100)

mask = np.array(Image.open('동그라미_이미지.png'))

font_path = 'NotoSansKR-Medium.ttf'

import seaborn as sns

def seaborn_color(word, font_size, position, orientation, font_path, random_state):
    cmap = sns.color_palette("ch:s=.25,rot=-.25", as_cmap=True)
    norm = plt.Normalize(vmin=0, vmax=255)
    color = cmap(norm(random.randint(0, 255)))  
    r, g, b, _ = [int(x * 255) for x in color]
    return f'rgb({r}, {g}, {b})'

wordcloud = WordCloud(font_path=font_path,
                      width=800, height=800,
                      background_color='white',
                      min_font_size=10,
                      collocations=False,
                      prefer_horizontal=0.5,
                      relative_scaling=0.5,
                      max_words=50,
                      stopwords=None,
                      mask=mask,
                      color_func=seaborn_color).generate_from_frequencies(dict(top_words))

plt.figure(figsize=(8, 8))
plt.imshow(wordcloud, interpolation='bilinear')
plt.axis("off")
plt.tight_layout(pad=0)
plt.show()

 

 

결과

 

 

다른 색으로도 해봤습니다.

mecab = Mecab()

# Advantage 열의 모든 리뷰를 하나의 문자열로 합침
all_reviews = ' '.join(df['Disadvantage'])

# 명사 추출
nouns = mecab.nouns(all_reviews)

word_counts = Counter(nouns)
top_words = word_counts.most_common(100)

mask = np.array(Image.open('동그라미_이미지.png'))

font_path = 'NotoSansKR-Medium.ttf'

def random_pastel_color(word, font_size, position, orientation, font_path, random_state):
    r = random.randint(180, 255)  # 민트 그린에서 라벤더 사이의 값
    g = random.randint(100, 180)  # 민트 그린에서 라벤더 사이의 값
    b = random.randint(100, 180)  # 핑크에서 블루 그레이 사이의 값
    return f'rgb({r}, {g}, {b})'

wordcloud = WordCloud(font_path=font_path,
                      width=800, height=800,
                      background_color='white',
                      min_font_size=10,
                      collocations=False,
                      prefer_horizontal=0.5,
                      relative_scaling=0.5,
                      max_words=50,
                      stopwords=None,
                      mask=mask,
                      color_func=random_pastel_color).generate_from_frequencies(dict(top_words))

plt.figure(figsize=(8, 8))
plt.imshow(wordcloud, interpolation='bilinear')
plt.axis("off")
plt.tight_layout(pad=0)
plt.show()

 

결과