[python] 파이썬 네이처언어 프로세싱 라이브러리를 이용한 키워드 감정 분석

감정 분석은 자연어 처리(Natural Language Processing, NLP)의 중요한 영역으로, 텍스트의 감정을 분석하여 긍정적, 부정적, 중립적 감정을 파악하는 작업입니다. 파이썬은 NLP 작업을 수행하기 위한 다양한 라이브러리를 제공하고 있으며, 그 중에서도 네이처언어 프로세싱(Natural Language Toolkit, NLTK) 라이브러리는 텍스트 분석에 많이 활용됩니다.

NLTK 소개

NLTK는 파이썬의 NLP를 위한 강력한 도구로, 토큰화, 형태소 분석, 품사 태깅, 구문 분석, 감정 분석 등의 다양한 기능을 제공합니다. NLTK를 사용하여 텍스트 데이터를 분석하고 감정을 파악할 수 있습니다.

텍스트의 전처리

NLTK를 사용하여 텍스트 데이터를 전처리하는 과정은 다음과 같습니다.

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

sentence = "This is an example sentence for emotion analysis."
tokens = word_tokenize(sentence)
tokens = [word.lower() for word in tokens if word.isalpha()]
stop_words = set(stopwords.words('english'))
tokens = [word for word in tokens if word not in stop_words]

lemmatizer = WordNetLemmatizer()
tokens = [lemmatizer.lemmatize(word) for word in tokens]

위의 코드는 NLTK를 사용하여 텍스트를 토큰화하고, 불용어를 제거하며, 단어를 원형으로 변환하는 과정을 보여줍니다.

감정 분석

NLTK를 사용하여 텍스트의 감정을 분석하는 방법은 다양하지만, 감정 사전을 사용하여 단어의 감정을 파악하는 방법이 일반적으로 활용됩니다.

from nltk.sentiment import SentimentIntensityAnalyzer

sentence = "I love using NLTK for sentiment analysis."
sid = SentimentIntensityAnalyzer()
scores = sid.polarity_scores(sentence)

if scores['compound'] > 0:
    print("Positive sentiment")
elif scores['compound'] < 0:
    print("Negative sentiment")
else:
    print("Neutral sentiment")

위의 코드는 NLTK의 SentimentIntensityAnalyzer를 사용하여 텍스트의 감정을 분석하고, 해당 감정이 긍정적인지, 부정적인지, 중립적인지를 판단하는 과정을 보여줍니다.

결론

NLTK는 파이썬을 사용하여 감정 분석을 수행하기 위한 강력한 도구로, 텍스트 데이터를 효과적으로 처리하고 감정을 분석할 수 있습니다. 이를 활용하여 텍스트 데이터의 감정을 파악하고, 해당 감정에 따른 의사 결정을 내리는 데 활용할 수 있습니다.

참고 자료