Python - 문자열의 구두점과 불용어를 뺀 값 벡터라이징 해보기


 

구두점, 불용어, 벡터라이징에 대한 개념은 앞서 포스팅했던 자료들로 더 상세한 설명을 확인 할 수 있습니다.

 

구두점 제거하기 : https://luvris2.tistory.com/62

 

문자열 함수 Punctuation - 문자열의 쉼표와 마침표 등의 구두점 제거하기

# String - Punctuation 문장의 데이터를 구분시 쉼표(,)나 마침표(.) 혹은 느낌표, 물음표 등의 구두점이 존재한다. 공백으로 문장의 데이터를 구분하기에는 이러한 구두점까지 같이 데이터에 포함이

luvris2.tistory.com

 

불용어 : https://luvris2.tistory.com/60

 

WordCloud(핵심 단어 시각화) 라이브러리의 활용 + STOPWORDS(불용어), CountVectorizer(문자열 수치화)

# WordCloud (핵심 단어 시각화) 문서의 문구와 단어를 분석하여 중요도나 사용빈도를 직관적으로 파악할 수 있도록 시각화하는 표현 기법 장점 : 사용자가 문서의 주요 키워드나 중요도를 한 눈에

luvris2.tistory.com

 

벡터라이징 : https://luvris2.tistory.com/63

 

CountVectorizer (문자열 수치화) 라이브러리 활용

# 카운트 벡터라이징 (Count Vectorizing) from sklearn.feature_extraction.text import CountVectorizer 호출 문서의 단어별 등장 횟수(출현 빈도)를 카운팅하여 수치화 하는 것 단어 추출 > 단어 정렬 > 정렬..

luvris2.tistory.com


구두점 제거, 불용어 처리, 카운트 벡터라이저 정리

구두점 제거 

import string
# 문자열 함수 호출

Test = 'Hello Mr. Future. I am so happy to be learning AI now~'
# 문자열 변수 선언

Test_punc_removed = []
# 구두점 제거한 문자열을 저장할 변수 초기화

for char in Test:
  if char not in string.punctuation:
    Test_punc_removed.append(char)
# punctuation을 이용하여 구두점 제거

Test_punc_removed_join = ''.join(Test_punc_removed)
# 구두점 검사를 하여 한글자씩 저장된 문자열 변수 join

불용어 처리

  • nltk : 자연어 처리를 위한 파이썬 라이브러리
import nltk
# 자연어 처리를 위한 라이브러리

nltk.download('stopwords')
# 불용어 다운로드

from nltk.corpus import stopwords
# 다운로드한 불용어 함수 사용

my_stopwords = stopwords.words('english')
# 불용어 처리 할 언어 : 영어

Test_punc_removed_join_clean = []
# 불용어 처리 후 저장할 문자열 변수 초기화

Test_punc_removed_join
>>> Hello Mr Future I am so happy to be learning AI now

for word in Test_punc_removed_join.split():
  if word.lower() not in my_stopwords:
    Test_punc_removed_join_clean.append(word)
# 소문자로 변경하여 단어별로 나누기
# my_stopwords 불용어의 목록을 검사
# 불용어가 아니면 단어 추가

Test_punc_removed_join_clean
>>> ['Hello', 'Mr', 'Future', 'happy', 'learning', 'AI']

카운터 벡터라이저

  • get_feature_names_out() : 문자열 수치화된 문자열들을 확인
from sklearn.feature_extraction.text import CountVectorizer
# 카운터 벡터라이저 라이브러리 호출

sample_data= [
              'This is the first document',
              'I loved them',
              'This document is the second document',
              'I am loving you',
              'And this is the third one'
] # 문자열 변수 선언

vec = CountVectorizer()
# 카운터 벡터라이저 변수 선언

X = vec.fit_transform(sample_data)
# sample_data의 데이터를 카운터 벡터라이저로 가공

X = X.toarray()
# 가공된 데이터 X를 배열화

X
>>> array([[0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0],
       [0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0],
       [0, 0, 2, 0, 1, 0, 0, 0, 1, 1, 0, 0, 1, 0],
       [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1],
       [0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 1, 1, 0]])
       
vec.get_feature_names_out()
>>> array(['am', 'and', 'document', 'first', 'is', 'loved', 'loving', 'one',
       'second', 'the', 'them', 'third', 'this', 'you'], dtype=object)

주어진 문자열 데이터를 구두점과 불용어를 제거하고 벡터라이징 해보자!

예시 데이터

  • 예시에 사용할 데이터프레임
  • 스팸 메시지를 구두점과 불용어를 제거하고 문자열 수치화 하기

emails.csv
8.54MB


소스 코드

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. join 으로 문자열 합치기
  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
  
message_cleaning('hello ~~! my name is, wow ! nice to meet you !@#$%^&')
>>> ['hello', 'name', 'wow', 'nice', 'meet']
# 함수 정상 작동 테스트

from sklearn.feature_extraction.text import CountVectorizer # 카운트 벡터라이저 라이브러리

vec = CountVectorizer(analyzer = message_cleaning)
# analyzer는 한글자, 단어, 사용자 지정 함수 사용
# 우리는 사전에 정의한 사용자 지정 함수를 사용

X = vec.fit_transform(spam_df['text'])
# 데이터프레임의 스팸메시지 구두점 제거, 불용어 처리, 문자열 수치화

X = X.toarray()
# 벡터 라이징 된 데이터 배열화
# 인공지능 머신러닝에 사용 될 수 있으므로 배열화 진행