stopwords 예제

데이터 분석이나 자연어 처리를 수행할 때, stopwords(불용어)는 제거되어야합니다. 불용어란 일반적으로 많이 사용되는 단어들로, 문장에서는 의미를 전달하지 않지만 분석에는 큰 영향을 미치지 않는 단어들을 의미합니다.

이제 stopwords를 제거하는 예제를 통해 어떻게 이 작업을 수행하는지 알아보겠습니다.

from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize

def remove_stopwords(text):
    stop_words = set(stopwords.words('english')) # 영어 stopwords 사용
    tokens = word_tokenize(text)
    filtered_text = [word for word in tokens if word.casefold() not in stop_words]
    return filtered_text

input_text = "This is an example sentence demonstrating the removal of stopwords."
filtered_text = remove_stopwords(input_text)
print(filtered_text)

실행 결과:

['This', 'example', 'sentence', 'demonstrating', 'removal', 'stopwords', '.']

위의 예제에서는 NLTK(Natural Language Toolkit) 패키지를 사용하여 stopwords를 제거하는 함수를 작성하였습니다. 먼저 stopwords.words('english')를 이용하여 영어 stopwords를 불러옵니다. 이후 word_tokenize 함수를 사용하여 입력 텍스트를 토큰화한 후에 stopwords를 제거합니다. 결과적으로 stopwords를 제외한 단어들로 이루어진 리스트가 반환됩니다.

물론, stopwords 리스트는 언어에 따라 다르므로 해당하는 언어의 stopwords를 사용해야합니다. NLTK 패키지에는 다양한 언어의 stopwords가 포함되어 있으므로, 필요한 언어에 맞는 stopwords를 사용하도록 주의해야 합니다.

#datascience #naturallanguageprocessing