Skip to content

문서 단어 행렬

데이터

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

데이터 앞부분

df.head()

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

df.shape

문서 단어 행렬

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
불용어 추가
stop_words = ENGLISH_STOP_WORDS | {'my_stop_word'}

행렬 만들기

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

dtm = cv.fit_transform(df['review'])
만들어진 dtm의 형태를 확인해보면 1000행, 500열
dtm.shape
단어 목록을 확인한다. 단어 목록은 dtm이 아닌 cv에 저장
cv.get_feature_names_out()

단어 빈도

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

dtm.sum(axis=0)

단어 빈도 데이터 프레임

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

빈도순 정렬

word_count.sort_values('빈도', ascending=False).head()
엑셀 파일로 저장:
word_count.to_excel('word_count.xlsx')