Computer >> 컴퓨터 >  >> 프로그래밍 >> Python

파이썬 NLTK로 불용어(Stop Words) 다루기: 설치부터 실전 예제까지


자연어 처리(NLP)와 불용어(Stop Words)의 개념

자연어 처리(Natural Language Processing, NLP)의 핵심 아이디어는 기계가 사람의 개입 없이도 텍스트를 일정 수준 이해하고 분석·처리할 수 있어야 한다는 것입니다. 즉, 텍스트가 무엇을 의미하거나 전달하려는지 어느 정도 파악하는 것이 목표입니다.

컴퓨터가 텍스트를 처리할 때는 문장 안에서 큰 의미가 없거나 상대적으로 덜 중요한 단어(데이터)를 걸러내야 합니다. NLTK에서는 이런 쓸모없는 단어들을 불용어(stop words)라고 부릅니다.

불용어를 미리 제거해 두면 데이터베이스의 저장 공간을 절약할 수 있고, 불필요한 처리 시간 낭비도 막을 수 있습니다. 분석 목적에 따라 직접 불용어 목록을 만들어 사용할 수도 있지만, NLTK는 기본적으로 불용어로 간주되는 단어들을 모아둔 코퍼스를 제공합니다.

필요한 라이브러리 설치

먼저 nltk 라이브러리가 필요합니다. 터미널에서 아래 명령어를 실행하세요.

$ pip install nltk

불용어 코퍼스나 토크나이저를 처음 사용한다면, 파이썬 셸에서 다음과 같이 관련 리소스를 먼저 내려받아야 할 수 있습니다.

>>> import nltk
>>> nltk.download('stopwords')
>>> nltk.download('punkt')

그다음 NLTK 코퍼스에서 불용어 목록에 접근할 수 있습니다.

>>> import nltk
>>> from nltk.corpus import stopwords

NLTK가 제공하는 영어 불용어 목록

아래는 NLTK가 기본으로 제공하는 영어 불용어 집합입니다.

>>> set(stopwords.words('english'))
{'not', 'other', 'shan', "hadn't", 'she', 'did', 'through', 'and', 'does', "that'll", "weren't", 'your', "should've", "hasn't", 'myself', 'should', 'because', 'wasn', 'what', 'to', 'this', 'was', 'more', 'y', 'again', "needn't", 'into', 'above', 'themselves', 'd', "won't", 'during', 'haven', 'both', "shan't", 'their', 'on', 'hadn', 'up', 'once', 'its', 'against', 'before', 't', 'while', 'needn', 'doing', "don't", 'yourselves', 'until', 'is', 'all', 's', 'will', "you've", 'being', 'under', 'they', 'ours', 'wouldn', 'of', 'didn', 'below', 'just', 'ma', 'yours', "you'll", 'mightn', 'where', 'are', 'that', 'those', 'most', 'them', 'if', 'you', "shouldn't", 'off', 'for', 'her', 'such', 'now', 'than', 're', 'no', 'm', 'or', "aren't", 'further', 'here', "wasn't", 'after', "haven't", 'my', 'himself', 'at', 'had', 'yourself', 'by', 'weren', 'only', 'have', 'we', 'do', 'same', "isn't", 'herself', 'll', 'down', 'then', 'why', 'own', 'him', 'so', 'having', 'nor', 'isn', 'few', 'how', 'each', 'there', 'with', 'couldn', 'about', 'very', 'am', 'me', "didn't", "doesn't", 'which', "she's", 'doesn', 'were', 'he', 'in', "mightn't", 'when', 'our', 'who', 'his', "couldn't", 'the', "you'd", 'be', 'hers', 'hasn', 'between', 'it', 'mustn', 'but', 'out', 'can', "wouldn't", 'ourselves', 'whom', 'been', 'these', 'aren', 'over', 'itself', 'a', 'i', 'too', 'theirs', 'some', "you're", 'as', 'won', "it's", 'from', 'o', 'don', 'any', 've', 'ain', 'has', 'an', "mustn't", 'shouldn'}

예제 코드: 문장에서 불용어 제거하기

아래 프로그램은 word_tokenize()로 문장을 토큰화한 뒤, 불용어 집합에 포함되지 않은 단어만 골라내는 전체 과정을 보여줍니다.

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

example_sent = "Python is a powerful high-level, object-oriented programming language created by Guido van Rossum."\
"It has simple easy-to-use syntax, making it the perfect language for someone trying to learn computer programming for the first time."\
"This is a comprehensive guide on how to get started in Python, why you should learn it and how you can learn it. However, if you knowledge "\
"of other programming languages and want to quickly get started with Python."

stop_words = set(stopwords.words('english'))

word_tokens = word_tokenize(example_sent)

filtered_sentence = [w for w in word_tokens if w not in stop_words]

print(word_tokens)
print(filtered_sentence)

리스트 컴프리헨션 대신 for 반복문을 사용하고 싶다면 다음과 같이 작성할 수도 있습니다.

filtered_sentence = []

for w in word_tokens:
    if w not in stop_words:
        filtered_sentence.append(w)

실행 결과

1) 불용어를 제거하지 않은 경우(원본 토큰)

['Python', 'is', 'a', 'powerful', 'high-level', ',', 'object-oriented', 'programming', 'language', 'created', 'by', 'Guido', 'van', 'Rossum.It', 'has', 'simple', 'easy-to-use', 'syntax', ',', 'making', 'it', 'the', 'perfect', 'language', 'for', 'someone', 'trying', 'to', 'learn', 'computer', 'programming', 'for', 'the', 'first', 'time.This', 'is', 'a', 'comprehensive', 'guide', 'on', 'how', 'to', 'get', 'started', 'in', 'Python', ',', 'why', 'you', 'should', 'learn', 'it', 'and', 'how', 'you', 'can', 'learn', 'it', '.', 'However', ',', 'if', 'you', 'knowledge', 'of', 'other', 'programming', 'languages', 'and', 'want', 'to', 'quickly', 'get', 'started', 'with', 'Python', '.']

2) 불용어를 제거한 경우

['Python', 'powerful', 'high-level', ',', 'object-oriented', 'programming', 'language', 'created', 'Guido', 'van', 'Rossum.It', 'simple', 'easy-to-use', 'syntax', ',', 'making', 'perfect', 'language', 'someone', 'trying', 'learn', 'computer', 'programming', 'first', 'time.This', 'comprehensive', 'guide', 'get', 'started', 'Python', ',', 'learn', 'learn', '.', 'However', ',', 'knowledge', 'programming', 'languages', 'want', 'quickly', 'get', 'started', 'Python', '.']

두 결과를 비교해 보면 'is', 'a', 'the', 'for', 'to', 'and' 같은 불용어가 모두 사라진 것을 확인할 수 있습니다. 이렇게 불용어를 제거하면 토큰 수가 줄어들어 이후 형태소 분석, 빈도 분석, 머신러닝 학습 등의 단계에서 저장 공간과 연산 비용을 크게 절약할 수 있습니다.