import numpy as np
import pandas as pd
import string
import nltk
nltk.download('stopwords')
from nltk.corpus import stopwords
my_stopwords = stopwords.words('english')

def message_cleaning(sentence):
    # 1. 구두점 제거
    Test_punc_removed = [char for char in sentence if char not in string.punctuation]
    # 2. 각 글자들을 하나의 문자열로 합친다.
    Test_punc_removed_join = ''.join(Test_punc_removed)
    # 3. 문자열에 불용어가 포함되어 있는지 확인해서, 불용어 제거한다.
    Test_punc_removed_join_clean = [word for word in Test_punc_removed_join.split() if word.lower() not in my_stopwords]
    # 4. 결과로 남은 단어들만 리턴한다.
    return Test_punc_removed_join_clean

from sklearn.feature_extraction.text import CountVectorizer
vec = CountVectorizer(analyzer = message_cleaning)

testing_sample = ['Hello, I am Ryan, I would like to book a hotel in Bali by January 24th', 'money viagara!!!!!']
X = vec.fit_transform(testing_sample)

X = X.toarray()
X

CountVectorizer를 import해주고 모델링 할 때 analyzer 파라미터에 문자열 전처리에 적용할 함수를 대입한다.

vec.fit_transform으로 대입한 문자열 데이터의 고유한 단어를 세서 각 개수를 Vectorize한다.

 

# 결과
[nltk_data] Downloading package stopwords to /root/nltk_data...
[nltk_data]   Package stopwords is already up-to-date!
array([[1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1],
       [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0]])

vec.transform에 새로운 문자열을 넣으면 이전에 계산한 고유한 단어들이 몇개 있는지 Vectorize한다.

new_date = ['Hello World!']
vec.transform(new_date).toarray()
# array([[0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0]])

 

+ Recent posts