컴퓨터가 자연어를 처리할 때, 사용자의 검색 의도와 문서를 매칭하는 데 큰 가치가 없는 극히 흔한 단어들은 어휘 목록에서 아예 제외됩니다. 이렇게 제외되는 단어들을 불용어(Stop Words)라고 부릅니다.
예를 들어 다음과 같은 입력 문장이 있다고 가정해 보겠습니다.
John is a person who takes care of the people around him.
불용어를 제거하면 다음과 같은 결과를 얻게 됩니다.
['John', 'person', 'takes', 'care', 'people', 'around', '.']
NLTK의 불용어 활용하기
NLTK는 이러한 불용어들의 컬렉션을 내장하고 있어, 주어진 문장에서 불용어를 손쉽게 제거할 수 있습니다. 불용어 데이터는 nltk.corpus 모듈 안에 포함되어 있으며, 이를 활용해 문장에서 불용어를 필터링할 수 있습니다.
예제 코드
from nltk.corpus import stopwords from nltk.tokenize import word_tokenize my_sent = "John is a person who takes care of people around him." tokens = word_tokenize(my_sent) filtered_sentence = [w for w in tokens if not w in stopwords.words()] print(filtered_sentence)
실행 결과
위 코드를 실행하면 다음과 같은 출력을 얻을 수 있습니다.
['John', 'person', 'takes', 'care', 'people', 'around', '.']
코드 설명
1. nltk.corpus에서 stopwords를 임포트하여 영어 불용어 목록에 접근합니다.
2. word_tokenize 함수로 입력 문장을 개별 토큰(단어) 단위로 분리합니다.
3. 리스트 컴프리헨션을 사용해 토큰 중 불용어 목록에 포함되지 않은 단어만 걸러냅니다.
4. 그 결과 'is', 'a', 'who', 'of', 'him' 같은 불용어가 제거된 핵심 단어들만 남게 됩니다.
참고로 최초 실행 시 nltk.download('stopwords')와 nltk.download('punkt') 명령으로 필요한 리소스를 먼저 다운로드해야 할 수 있습니다.