[python] NLTK를 사용해 불용어 처리를 어떻게 할 수 있나요?

NLTK(자연어 처리 툴킷)를 설치합니다.

!pip install nltk

필요한 모듈을 가져옵니다.

import nltk
from nltk.corpus import stopwords

불용어 리스트를 다운로드합니다.

nltk.download('stopwords')

불용어 처리를 위한 함수를 만듭니다.

def remove_stopwords(text):
    # 영어 불용어 리스트를 가져옵니다.
    stop_words = set(stopwords.words("english"))
    
    # 텍스트를 소문자로 변환합니다.
    text = text.lower()
    
    # 텍스트를 단어로 분리합니다.
    words = nltk.word_tokenize(text)
    
    # 불용어가 아닌 단어만 필터링합니다.
    filtered_words = [word for word in words if word not in stop_words]
    
    # 필터링된 단어들을 공백으로 구분하여 문자열로 반환합니다.
    filtered_text = " ".join(filtered_words)
    
    return filtered_text

불용어 처리를 적용합니다.

text = "This is an example sentence that needs stop word removal."
filtered_text = remove_stopwords(text)
print(filtered_text)

위의 코드는 NLTK를 사용해 영어에서 불용어를 제거하는 방법을 보여줍니다. 불용어란 텍스트에서 의미를 거의 가지지 않는 단어들을 말합니다. 이러한 불용어는 텍스트 분석이나 자연어 처리 작업에서 제외되어야 합니다.

위의 코드를 실행하면 “This example sentence needs stop word removal”라는 결과를 얻습니다. 이전의 텍스트에서 “is”, “an”, “that”과 같은 불용어가 제거되었음을 볼 수 있습니다.

NLTK는 다양한 언어의 불용어 리스트를 제공하며, 한국어 역시 포함되어 있습니다. 한국어 불용어 처리를 위해서는 stopwords.words("korean")를 사용하면 됩니다.

참고 문서: