Skip to content

문서 단어 행렬

데이터

import pandas as pd
df = pd.read_excel('yelp.xlsx')

데이터 앞부분

df.head()
review sentiment
0 Wow... Loved this place. 1
1 Crust is not good. 0
2 Not tasty and the texture was just nasty. 0
3 Stopped by during the late May bank holiday of... 1
4 The selection on the menu was great and so wer... 1

데이터의 형태(1000행, 2열)

df.shape
(1000, 2)

문서 단어 행렬

from sklearn.feature_extraction.text import CountVectorizer
cv = CountVectorizer(max_features=500, stop_words='english')
  • max_features: 문서단어행렬에 포함시킬 최대(max)의 단어(feature) 수
  • stop_words: 분석에서 제외할 불용어를 설정
    • english로 설정하면 영어의 경우 관사, 전치사 등을 제외
    • 다른 언어는 리스트 등의 형태로 불용어 목록을 넘겨주어야

불용어

영어 불용어 목록 보기

from sklearn.feature_extraction.text import ENGLISH_STOP_WORDS
ENGLISH_STOP_WORDS
frozenset({'a',
           'about',
           'above',
           'across',
           'after',

...

불용어 추가

stop_words = ENGLISH_STOP_WORDS | {'my_stop_word'}

행렬 만들기

df의 review 컬럼을 바탕으로 문서 단어 행렬을 만든다.

dtm = cv.fit_transform(df['review'])

만들어진 dtm의 형태를 확인해보면 1000행, 500열

dtm.shape
(1000, 500)

단어 목록을 확인한다. 단어 목록은 dtm이 아닌 cv에 저장

cv.get_feature_names_out()
array(['10', '100', '12', '20', '30', '35', '40', 'absolutely', 'ago',
       'amazing', 'ambiance', 'ambience', 'anytime', 'area', 'arrived',
       'ask', 'asked', 'ate', 'atmosphere', 'attentive', 'authentic',
       'average', 'avoid', 'away', 'awesome', 'awful', 'bacon', 'bad',
       'bar', 'barely', 'basically', 'bathroom', 'batter', 'bay', 'beans',

...

단어 빈도

단어별 총빈도(axis=1: 행별 합계)

dtm.sum(axis=0)
matrix([[  5,   2,   2,   4,   5,   3,   4,   8,   3,  24,   7,   3,   5,
           7,   3,   4,   5,   3,  11,   7,   6,   4,   5,   5,  12,   3,
           5,  18,   7,   5,   2,   3,   2,   4,   3,   4,   3,   5,   8,
           3,   2,  30,  16,   3,   2,   2,   8,   2,   2,   2,  11,   3,
           5,  10,   5,   3,   3,  11,  12,   4,   4,   3,   3,   3,  20,

...

단어 빈도 데이터 프레임

word_count = pd.DataFrame({
    '단어': cv.get_feature_names_out(),
    '빈도': dtm.sum(axis=0).flat
})

빈도순 정렬

word_count.sort_values('빈도', ascending=False).head()
단어 빈도
156 food 126
316 place 106
175 good 95
389 service 85
178 great 70

엑셀 파일로 저장:

word_count.to_excel('word_count.xlsx')