개발공부

문자열 데이터의 구두점과 Stopwords(불용어) 제거하기 본문

Python/Machine Learning

문자열 데이터의 구두점과 Stopwords(불용어) 제거하기

mscha 2022. 5. 11. 17:30

구두점 제거

아래와 같은 테스트 문자열의 구두점을 제거해보자.

Test = 'Here is a mini challenge, that will teach you how to remove stopwords and punctuations!'

파이썬의 string은 구두점을 제공해준다.

import string
string.punctuation

제거하는 코드는 다음과 같다.

Test_punc_removed = [char for char in Test if char not in string.punctuation]
Test_punc_removed_join = ''.join(Test_punc_removed)
Test_punc_removed_join​

그럼 아래와같은 결과를 얻는다.

 

StopWords (불용어) 제거

nltk라이브러리를 통해 stopwords를 가져올 수 있다.

import nltk
nltk.download('stopwords')
from nltk.corpus import stopwords

my_stopwords = stopwords.words('english')

Test_punc_removed_join_clean = []
for word in Test_punc_removed_join.split() :
  if word.lower() not in my_stopwords :
    Test_punc_removed_join_clean.append(word)
    
Test_punc_removed_join_clean

 

이제 위의 두가지 단계를 하나의 함수로 만들어보면 아래와 같이 만들 수 있다.

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