[python] NLTK를 사용해 문서 분석을 수행하는 방법은 무엇인가요?
- NLTK 설치: 먼저 NLTK를 설치해야 합니다. 아래의 명령어를 사용하여 NLTK를 설치할 수 있습니다.
pip install nltk
- 토큰화(Tokenization): 문서를 단어 또는 문장으로 분할하는 토큰화 작업을 수행해야 합니다. NLTK는 다양한 토큰화 메서드를 제공합니다. 예를 들어, 문장 토큰화를 위해
sent_tokenize()
함수를 사용할 수 있고, 단어 토큰화를 위해word_tokenize()
함수를 사용할 수 있습니다.
from nltk.tokenize import sent_tokenize, word_tokenize
text = "NLTK를 사용해 문서 분석을 수행하는 방법을 알아보겠습니다."
sentences = sent_tokenize(text)
words = word_tokenize(text)
print(sentences)
print(words)
결과:
['NLTK를 사용해 문서 분석을 수행하는 방법을 알아보겠습니다.']
['NLTK를', '사용해', '문서', '분석을', '수행하는', '방법을', '알아보겠습니다', '.']
- 형태소 분석(Morphological Analysis): 단어를 형태소로 분석하여 어근, 접두사, 접미사 등과 같이 구성 요소로 나누는 작업입니다. NLTK는 다양한 형태소 분석기를 제공합니다. 예를 들어, 영어 형태소 분석을 위해
nltk.pos_tag()
함수를 사용할 수 있습니다.
from nltk.tokenize import word_tokenize, pos_tag
words = word_tokenize("I love NLTK!")
tags = pos_tag(words)
print(tags)
결과:
[('I', 'PRP'), ('love', 'VBP'), ('NLTK', 'NNP'), ('!', '.')]
- 불용어 제거(Stopword Removal): 불용어는 문장에서 제거해야 하는 빈번하게 등장하지만 분석에 도움이 되지 않는 단어입니다. NLTK는 다양한 언어의 불용어 목록을 제공합니다. 예를 들어, 영어 불용어를 제거하기 위해
nltk.corpus.stopwords.words('english')
를 사용할 수 있습니다.
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
stop_words = set(stopwords.words('english'))
text = "I love NLTK, it's an amazing tool for natural language processing."
words = word_tokenize(text)
filtered_words = [word for word in words if word.lower() not in stop_words]
print(filtered_words)
결과:
['I', 'love', 'NLTK', ',', "'s", 'amazing', 'tool', 'natural', 'language', 'processing', '.']
NLTK를 사용하면 이외에도 다양한 문서 분석 작업을 수행할 수 있습니다. NLTK의 기능을 잘 활용하여 자연어 처리를 수행해보세요.
- NLTK 공식 문서: nltk.org
- NLTK 토큰화 메서드: nltk.org/api/nltk.tokenize.html
- NLTK 형태소 분석 메서드: nltk.org/api/nltk.tag.html
- NLTK 불용어 목록: nltk.org/book/ch02.html#wordlist-corpora