[python] 파이썬과 자연어 처리를 이용한 텍스트 분류 및 감정 분석

자연어 처리(Natural Language Processing, NLP)는 기계 학습과 인공 지능의 한 분야로, 컴퓨터가 인간의 언어를 이해하고 분석하는 데 사용됩니다. 파이썬을 사용하여 텍스트 데이터를 분류하고 감정을 분석하는 방법을 알아봅시다.

1. 텍스트 분류(Text Classification)

텍스트 분류는 텍스트를 사전 정의된 범주에 할당하는 과정입니다. 예를 들어, 스팸 메일 필터링, 뉴스 기사 분류, 감성 분석 등에 활용됩니다. 파이썬의 scikit-learn 라이브러리와 NLP 라이브러리인 NLTK를 활용하여 텍스트 분류를 수행할 수 있습니다.

from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.naive_bayes import MultinomialNB
from sklearn.pipeline import make_pipeline
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
import nltk
nltk.download('punkt')

# 텍스트 데이터
text_data = ["This is a good book.", "That movie was terrible.", "This restaurant has great food."]

# 벡터화 및 모델 학습
model = make_pipeline(TfidfVectorizer(stop_words=stopwords.words('english'), tokenizer=word_tokenize), MultinomialNB())
model.fit(text_data, [1, 0, 1])

# 새로운 데이터 분류
new_text = ["I love the food at this restaurant!"]
predicted_category = model.predict(new_text)
print(predicted_category)

2. 감정 분석(Sentiment Analysis)

감정 분석은 주어진 텍스트의 감정을 파악하는 과정으로, 긍정적, 부정적 또는 중립적인 감정을 분석합니다. 파이썬의 nltk 라이브러리와 VADER 감정 사전을 활용하여 감정 분석을 수행할 수 있습니다.

from nltk.sentiment.vader import SentimentIntensityAnalyzer

# 감정 분석 모델 초기화
sid = SentimentIntensityAnalyzer()

# 감정 분석 수행
sentence = "I love the new iPhone."
polarity_scores = sid.polarity_scores(sentence)
print(polarity_scores)

결론

파이썬과 자연어 처리 기술을 조합하여 텍스트 분류와 감정 분석을 수행할 수 있습니다. 이를 통해 텍스트 데이터에서 유용한 통찰을 얻을 수 있으며, 다양한 응용 프로그램에 적용할 수 있습니다.

참고 자료