데이터 분석/키워드 분석

[실습] 텍스트 시각화

toraa 2025. 1. 23. 10:20

pre_text.csv 의 텍스트 데이터를 활용하여 자유롭게 시각화 분석 해보기

(필요시 불용어 제거 등 전처리 추가)

 

1. 빈도그래프 만들기

import pandas as pd

st_df = pd.read_csv('./data/pre_text.csv').dropna()
st_df
from sklearn.feature_extraction.text import CountVectorizer
import numpy as np

cvec = CountVectorizer(max_df=0.9, min_df=3, analyzer = 'word',
                      )
X = cvec.fit_transform(st_df['clean'])
x = X.toarray()
x.shape


(693, 146)

처음엔 토큰 수가 너무 작게 나왔는데, min_df를 20으로 너무 높게 잡아서였다.

min_df=3으로 줄였더니 토큰을 충분히 얻었다.

 

names = cvec.get_feature_names_out()
names
xsum = np.sum(x, axis=0)
xsum
rank_ind = np.argsort(xsum)
rank_ind

argsort() 함수 활용도 많고 중요하니 잘 숙지하

 

'스타','벅스' 단어를 불용어로 제거하고 싶어서 필터링을 해주었다.

most_n = []
most_v = []

all_keywords = names  # CountVectorizer로 추출된 전체 단어 리스트

# 제외할 단어 리스트
exclude_keywords = ['스타', '벅스']  # 제외하고 싶은 단어 추가

# 제외 단어를 기준으로 필터링
filtered_keywords = [word for word in all_keywords if word not in exclude_keywords]

for ind in rank_ind[-10: ]:
    most_n.append(filtered_keywords[ind])
    most_v.append(xsum[ind])
print(most_n)
print(most_v)
['집중', '공부', '이벤트', '베이글', '시간', '사용', '자주', '매장', '케익', '카페']
[19, 27, 28, 29, 30, 31, 33, 41, 49, 86]
import matplotlib.pyplot as plt

plt.rc('font', family='Malgun Gothic')

plt.figure(figsize=(6,5))
fcolor = '#37474F'
gcolor = '#F48FB1'

ax = plt.subplot()
hbars = ax.barh(most_n, most_v, height=0.7, color=gcolor)

ax = plt.subplot()
hbars = ax.barh(most_n, most_v, height=0.7, color=gcolor) #y는 most_n, x는 most_v
ax.set_title('빈도그래프', fontsize=20)

ax.tick_params(axis='both', labelsize=10, labelcolor=fcolor) 

ax.spines['right'].set_visible(False)
ax.spines['left'].set_visible(False)

ax.bar_label(hbars, fmt='%g', padding=8, color=gcolor, fontsize=10)

plt.show()

 

2. 워드클라우드 만들기

from wordcloud import WordCloud
import numpy as np

wc = WordCloud(font_path='./gulim.ttc',  
               background_color="white", 
               collocations=False,     
               width=800,                
               height=800,            
               scale=1)                  

wc.generate(' '.join(st_df['clean']))
import matplotlib.pyplot as plt

plt.figure(figsize=(5,5))

ax = plt.subplot()
ax.imshow(wc)

ax.set_title('스타벅스', fontsize=20)

for i in 'top bottom right left'.split():
    ax.spines[i].set_visible(False)

ax.tick_params(left=False, right=False, labelleft=False,
               labelbottom=False, bottom=False)

plt.show()

 

마스크를 설정하여 모양 바꾸기

from PIL import Image

image = Image.open("./img/커피잔.png").convert("RGBA")  # 알파 채널 포함
background = Image.new("RGBA", image.size, (255, 255, 255))  # 흰색 배경 생성
image = Image.alpha_composite(background, image).convert("L")  # 흑백 변환
mask_image = np.array(image)

wc = WordCloud(mask = mask_image,
               font_path='./gulim.ttc',
               background_color='white',
               collocations=False, width=800, height=800, scale=1)

wc.generate(' '.join(st_df['clean'].to_numpy()))

plt.figure(figsize=(5,5))
ax = plt.subplot()
ax.imshow(wc)
ax.set_title('스타벅스', fontsize=20)

for i in 'top bottom right left'.split():
    ax.spines[i].set_visible(False)

ax.tick_params(left=False, right=False, labelleft=False,
               labelbottom=False, bottom=False)

plt.show()

처음에 마스크 이미지를 아이콘png파일을 사용하다보니 적용이 안되었다.

그래서 알파채널포함하여 흰색배경을 생성하고, 흑백 변환을 했더니 마스크가 적용되었다