Ver3.0 파이썬으로 뉴스기사 감정 분석기 만들기

파이썬으로 뉴스기사 감정 분석기 만들기
아니면 "이 기자 완전 긍정적으로 쓴 거 같은데"라고 느낀 적 있을 거야.
근데 이걸 사람이 일일이 판단하는 게 아니라 AI가 자동으로 분석해준다면?
오늘은 바로 그 기술, 감정 분석(Sentiment Analysis)을 파이썬으로 직접 구현해보는 방법을 알려줄게 ㅎㅎ
이 기술은 요즘 진짜 핫해서 마케팅, 여론 조사, 주식 투자 분석 등 다양한 분야에서 쓰이고 있어.
재능넷 같은 플랫폼에서도 이런 AI 개발 재능을 공유하는 사람들이 점점 늘어나고 있다니까! 🚀
🎯 감정 분석이 뭔데?
감정 분석은 텍스트에 담긴 감정이나 의견을 자동으로 파악하는 기술이야.쉽게 말하면 AI가 글을 읽고 "이거 긍정적이네, 부정적이네, 중립적이네"를 판단하는 거지 ㅋㅋ
부정(Negative): 나쁘다, 실망스럽다, 문제다 등의 부정적 표현
중립(Neutral): 객관적 사실 전달, 감정 표현이 없는 경우
왜냐면 같은 사건도 언론사마다 다르게 표현하거든? 😏
예를 들어볼게:
A 언론: "경제 성장률 급상승! 전문가들 환호"
B 언론: "경제 성장률 상승에도 불구하고 서민 경제는 여전히 어려워"
같은 사건인데 완전 다른 느낌이지? 이런 걸 AI가 자동으로 분석해주는 거야! 🎉
🛠️ 필요한 도구들 준비하기
본격적으로 시작하기 전에 필요한 라이브러리들을 설치해야 해.파이썬 환경이 이미 설정되어 있다고 가정하고 진행할게!
STEP 1
기본 라이브러리 설치
pip install numpy pandas
pip install beautifulsoup4 requests
pip install konlpy
pip install scikit-learn
pip install textblob
pip install newspaper3k
• numpy, pandas: 데이터 처리 및 분석
• beautifulsoup4, requests: 웹 크롤링으로 뉴스 수집
• konlpy: 한글 자연어 처리 (형태소 분석)
• scikit-learn: 머신러닝 알고리즘
• textblob: 영어 감정 분석
• newspaper3k: 뉴스 기사 추출
Windows 사용자는 Java JDK를 먼저 설치해야 하고,
Mac 사용자는 Xcode Command Line Tools가 필요해.
설치 중 에러가 나면 공식 문서를 꼭 확인해봐!
감정 분석 전용 라이브러리
한글 감정 분석을 위해서는 추가 라이브러리가 필요해:pip install soynlp
pip install transformers
pip install torch
• transformers: BERT 같은 최신 딥러닝 모델 사용
• torch: PyTorch 딥러닝 프레임워크
커피 한 잔 하고 오면 딱이야 ☕
📝 기본 감정 분석기 만들기
자, 이제 본격적으로 코드를 작성해볼 거야!먼저 간단한 버전부터 시작해서 점점 고도화시켜보자 💪
STEP 3
영어 뉴스 감정 분석 (기초)
영어는 이미 잘 만들어진 라이브러리가 많아서 시작하기 쉬워:from textblob import TextBlob
import requests
from newspaper import Article
def analyze_english_news(url):
"""영어 뉴스 기사 감정 분석"""
# 뉴스 기사 가져오기
article = Article(url)
article.download()
article.parse()
# 제목과 본문 추출
title = article.title
text = article.text
# 감정 분석
blob = TextBlob(text)
polarity = blob.sentiment.polarity # -1(부정) ~ 1(긍정)
subjectivity = blob.sentiment.subjectivity # 0(객관) ~ 1(주관)
# 결과 판단
if polarity > 0.1:
sentiment = "긍정적 😊"
elif polarity < -0.1:
sentiment = "부정적 😞"
else:
sentiment = "중립적 😐"
print(f"제목: {title}")
print(f"감정: {sentiment}")
print(f"극성 점수: {polarity:.3f}")
print(f"주관성 점수: {subjectivity:.3f}")
return {
'title': title,
'sentiment': sentiment,
'polarity': polarity,
'subjectivity': subjectivity
}
# 사용 예시
url = "https://www.bbc.com/news/business-12345678"
result = analyze_english_news(url)
• 1에 가까울수록 매우 긍정적
• -1에 가까울수록 매우 부정적
• 0 근처면 중립적
Subjectivity (주관성): 의견의 주관적 정도
• 1에 가까울수록 주관적 의견
• 0에 가까울수록 객관적 사실
TextBlob이 알아서 다 해주니까 몇 줄만으로도 감정 분석이 가능해!
근데 문제는... 한글은 이렇게 쉽지 않다는 거야 😅
한글 뉴스 감정 분석 (중급)
한글은 영어보다 훨씬 복잡해.형태소 분석도 해야 하고, 감정 사전도 직접 만들어야 하거든.
먼저 간단한 감정 사전 기반 분석기를 만들어볼게:
from konlpy.tag import Okt
from collections import Counter
import re
class KoreanSentimentAnalyzer:
def __init__(self):
self.okt = Okt()
# 감정 사전 (실제로는 더 많은 단어 필요)
self.positive_words = {
'좋다', '훌륭하다', '최고', '만족', '성공', '발전', '상승',
'개선', '긍정', '희망', '기쁘다', '행복', '환영', '축하',
'우수', '탁월', '효과적', '혁신', '성장', '증가'
}
self.negative_words = {
'나쁘다', '최악', '실망', '실패', '하락', '감소', '악화',
'부정', '우려', '슬프다', '불행', '반대', '비판', '문제',
'위험', '손실', '피해', '충격', '불안', '걱정'
}
def preprocess(self, text):
"""텍스트 전처리"""
# 특수문자 제거
text = re.sub(r'[^\w\s]', ' ', text)
# 공백 정리
text = ' '.join(text.split())
return text
def analyze(self, text):
"""감정 분석 수행"""
# 전처리
text = self.preprocess(text)
# 형태소 분석
morphs = self.okt.morphs(text)
nouns = self.okt.nouns(text)
# 감정 단어 카운트
pos_count = sum(1 for word in morphs if word in self.positive_words)
neg_count = sum(1 for word in morphs if word in self.negative_words)
# 점수 계산
total = pos_count + neg_count
if total == 0:
sentiment = "중립"
score = 0
else:
score = (pos_count - neg_count) / total
if score > 0.2:
sentiment = "긍정"
elif score < -0.2:
sentiment = "부정"
else:
sentiment = "중립"
return {
'sentiment': sentiment,
'score': score,
'positive_count': pos_count,
'negative_count': neg_count,
'keywords': Counter(nouns).most_common(10)
}
# 사용 예시
analyzer = KoreanSentimentAnalyzer()
news_text = """
한국 경제가 예상을 뛰어넘는 성장세를 보이며 전문가들을 놀라게 했다.
특히 수출 부문에서 훌륭한 성과를 거두며 긍정적인 전망이 이어지고 있다.
정부는 이러한 성장세가 지속될 것으로 기대하고 있다.
"""
result = analyzer.analyze(news_text)
print(f"감정: {result['sentiment']}")
print(f"점수: {result['score']:.3f}")
print(f"긍정 단어: {result['positive_count']}개")
print(f"부정 단어: {result['negative_count']}개")
print(f"주요 키워드: {result['keywords']}")
1. 전처리: 특수문자 제거, 공백 정리
2. 형태소 분석: Okt를 사용해 단어 단위로 분리
3. 감정 단어 매칭: 미리 정의한 사전과 비교
4. 점수 계산: (긍정 단어 수 - 부정 단어 수) / 전체 감정 단어 수
5. 키워드 추출: 명사 빈도 분석
단점은 감정 사전을 계속 업데이트해야 하고, 문맥을 제대로 파악 못 한다는 거지 🤔
예를 들어 "좋지 않다"라는 표현은 '좋다'가 들어가서 긍정으로 잘못 분류될 수 있어.
이런 문제를 해결하려면 더 고급 기술이 필요해!
머신러닝 기반 감정 분석 (고급)
이제 진짜 제대로 된 머신러닝 모델을 만들어볼 거야!학습 데이터가 있다면 훨씬 정확한 분석이 가능해 😎
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import MultinomialNB
from sklearn.metrics import classification_report, accuracy_score
from konlpy.tag import Okt
import pandas as pd
import pickle
class MLSentimentAnalyzer:
def __init__(self):
self.okt = Okt()
self.vectorizer = TfidfVectorizer(
max_features=5000,
ngram_range=(1, 2)
)
self.model = MultinomialNB()
def tokenize(self, text):
"""한글 토큰화"""
return ' '.join(self.okt.morphs(text))
def train(self, texts, labels):
"""모델 학습"""
# 텍스트 토큰화
tokenized_texts = [self.tokenize(text) for text in texts]
# 학습/테스트 데이터 분리
X_train, X_test, y_train, y_test = train_test_split(
tokenized_texts, labels, test_size=0.2, random_state=42
)
# TF-IDF 벡터화
X_train_vec = self.vectorizer.fit_transform(X_train)
X_test_vec = self.vectorizer.transform(X_test)
# 모델 학습
self.model.fit(X_train_vec, y_train)
# 성능 평가
y_pred = self.model.predict(X_test_vec)
accuracy = accuracy_score(y_test, y_pred)
print(f"모델 정확도: {accuracy:.3f}")
print("\n분류 리포트:")
print(classification_report(y_test, y_pred))
return accuracy
def predict(self, text):
"""감정 예측"""
tokenized = self.tokenize(text)
vectorized = self.vectorizer.transform([tokenized])
prediction = self.model.predict(vectorized)[0]
probability = self.model.predict_proba(vectorized)[0]
return {
'sentiment': prediction,
'confidence': max(probability),
'probabilities': {
'positive': probability[1] if len(probability) > 1 else 0,
'negative': probability[0] if len(probability) > 0 else 0
}
}
def save_model(self, filepath):
"""모델 저장"""
with open(filepath, 'wb') as f:
pickle.dump({
'vectorizer': self.vectorizer,
'model': self.model
}, f)
def load_model(self, filepath):
"""모델 불러오기"""
with open(filepath, 'rb') as f:
data = pickle.load(f)
self.vectorizer = data['vectorizer']
self.model = data['model']
# 사용 예시 (학습 데이터가 있다고 가정)
analyzer = MLSentimentAnalyzer()
# 예시 학습 데이터
train_texts = [
"이 제품 정말 좋아요! 강력 추천합니다",
"최악이에요. 돈 아깝습니다",
"그냥 그래요. 보통입니다",
# ... 실제로는 수천~수만 개의 데이터 필요
]
train_labels = [
"positive",
"negative",
"neutral",
# ...
]
# 모델 학습
analyzer.train(train_texts, train_labels)
# 예측
news_text = "경제 성장률이 예상을 뛰어넘으며 긍정적인 신호를 보이고 있다"
result = analyzer.predict(news_text)
print(f"감정: {result['sentiment']}")
print(f"신뢰도: {result['confidence']:.3f}")
쉽게 말하면 "이 단어가 이 문서에서 얼마나 중요한가?"를 수치화하는 거지.
TF (단어 빈도): 문서 내에서 단어가 나온 횟수
IDF (역문서 빈도): 전체 문서에서 그 단어가 얼마나 희귀한지
자주 나오지만 모든 문서에 다 있는 단어(예: '이', '그', '저')는 점수가 낮고,
특정 문서에만 자주 나오는 단어는 점수가 높아져!
왜냐면 실제 데이터에서 패턴을 학습하니까! 🎯
근데 문제는 좋은 학습 데이터를 구하기가 쉽지 않다는 거야.
수천 개의 뉴스 기사에 일일이 긍정/부정 라벨을 붙여야 하거든 ㅠㅠ
🌟 최신 딥러닝 모델 활용하기
요즘 대세는 BERT 같은 트랜스포머 모델이야!이건 진짜 사람처럼 문맥을 이해할 수 있어서 정확도가 엄청 높아 🚀
STEP 6
한국어 BERT 모델 사용하기
from transformers import AutoTokenizer, AutoModelForSequenceClassification
import torch
import numpy as np
class BERTSentimentAnalyzer:
def __init__(self, model_name="beomi/kcbert-base"):
"""
한국어 BERT 모델 초기화
beomi/kcbert-base: 한국어 댓글로 학습된 BERT
"""
self.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
self.tokenizer = AutoTokenizer.from_pretrained(model_name)
# 사전 학습된 모델 로드 (감정 분석용으로 파인튜닝 필요)
# 여기서는 개념 설명을 위한 예시
self.model = AutoModelForSequenceClassification.from_pretrained(
model_name,
num_labels=3 # 긍정, 부정, 중립
)
self.model.to(self.device)
def predict(self, text, max_length=512):
"""감정 예측"""
# 토큰화
inputs = self.tokenizer(
text,
return_tensors="pt",
truncation=True,
max_length=max_length,
padding=True
)
# GPU로 이동
inputs = {k: v.to(self.device) for k, v in inputs.items()}
# 예측
self.model.eval()
with torch.no_grad():
outputs = self.model(**inputs)
logits = outputs.logits
probabilities = torch.softmax(logits, dim=1)
# 결과 해석
probs = probabilities.cpu().numpy()[0]
predicted_class = np.argmax(probs)
sentiment_map = {0: "부정", 1: "중립", 2: "긍정"}
return {
'sentiment': sentiment_map[predicted_class],
'confidence': float(probs[predicted_class]),
'probabilities': {
'negative': float(probs[0]),
'neutral': float(probs[1]),
'positive': float(probs[2])
}
}
def analyze_news_batch(self, news_list):
"""여러 뉴스 기사 일괄 분석"""
results = []
for news in news_list:
result = self.predict(news)
results.append(result)
return results
# 사용 예시
analyzer = BERTSentimentAnalyzer()
news_text = """
한국 경제가 3분기 연속 성장세를 이어가며 전문가들의 긍정적인 평가를 받고 있다.
특히 반도체 수출이 급증하면서 무역수지 개선에 크게 기여했다.
정부는 이러한 추세가 내년까지 지속될 것으로 전망하고 있다.
"""
result = analyzer.predict(news_text)
print(f"감정: {result['sentiment']}")
print(f"신뢰도: {result['confidence']:.1%}")
print(f"긍정 확률: {result['probabilities']['positive']:.1%}")
print(f"부정 확률: {result['probabilities']['negative']:.1%}")
print(f"중립 확률: {result['probabilities']['neutral']:.1%}")
2. 메모리 사용량: BERT는 메모리를 많이 먹어. 최소 8GB RAM 권장
3. 파인튜닝 필요: 위 코드는 기본 모델이라 실제로는 감정 분석 데이터로 추가 학습이 필요해
4. 토큰 길이 제한: BERT는 최대 512 토큰까지만 처리 가능. 긴 기사는 잘라야 해
"이 제품 좋지 않아요"라는 문장도 제대로 부정으로 분류할 수 있지! 😊
재능넷 같은 플랫폼에서 AI 개발 재능을 공유하는 사람들도
요즘은 이런 최신 모델을 활용한 서비스를 많이 제공하더라고 ㅎㅎ
📰 실전: 뉴스 크롤링부터 분석까지
이제 진짜 실전이야!뉴스 사이트에서 기사를 가져와서 감정 분석까지 한 번에 해보자 💪
STEP 7
네이버 뉴스 크롤러 만들기
import requests
from bs4 import BeautifulSoup
import time
from datetime import datetime
import pandas as pd
class NaverNewsCrawler:
def __init__(self):
self.headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
}
def get_news_list(self, keyword, max_count=10):
"""키워드로 뉴스 검색"""
news_list = []
# 네이버 뉴스 검색 URL
base_url = "https://search.naver.com/search.naver"
params = {
'where': 'news',
'query': keyword,
'sort': 0 # 관련도순
}
try:
response = requests.get(base_url, params=params, headers=self.headers)
soup = BeautifulSoup(response.text, 'html.parser')
# 뉴스 항목 찾기
news_items = soup.select('.news_area')
for item in news_items[:max_count]:
try:
# 제목과 링크
title_elem = item.select_one('.news_tit')
title = title_elem.text.strip()
link = title_elem['href']
# 요약
summary_elem = item.select_one('.news_dsc')
summary = summary_elem.text.strip() if summary_elem else ""
# 언론사
press_elem = item.select_one('.info.press')
press = press_elem.text.strip() if press_elem else ""
news_list.append({
'title': title,
'link': link,
'summary': summary,
'press': press,
'keyword': keyword,
'crawled_at': datetime.now()
})
except Exception as e:
print(f"항목 파싱 오류: {e}")
continue
time.sleep(1) # 서버 부하 방지
except Exception as e:
print(f"크롤링 오류: {e}")
return news_list
def get_news_content(self, url):
"""뉴스 본문 가져오기"""
try:
response = requests.get(url, headers=self.headers)
soup = BeautifulSoup(response.text, 'html.parser')
# 네이버 뉴스 본문 (사이트마다 다를 수 있음)
article = soup.select_one('#dic_area')
if article:
# 불필요한 태그 제거
for tag in article.find_all(['script', 'style']):
tag.decompose()
return article.get_text(strip=True)
except Exception as e:
print(f"본문 추출 오류: {e}")
return None
# 사용 예시
crawler = NaverNewsCrawler()
news_list = crawler.get_news_list("경제성장", max_count=5)
for news in news_list:
print(f"제목: {news['title']}")
print(f"언론사: {news['press']}")
print(f"요약: {news['summary'][:100]}...")
print("-" * 80)
2. 이용약관 준수: 각 사이트의 이용약관을 지켜야 해
3. 서버 부하 최소화: 요청 사이에 적절한 딜레이 추가
4. 개인정보 보호: 수집한 데이터의 개인정보 처리 주의
5. 상업적 이용: 상업적으로 사용하려면 별도 허가 필요할 수 있어
통합 뉴스 감정 분석 시스템
이제 크롤링과 감정 분석을 합쳐서 완전한 시스템을 만들어보자!import pandas as pd
from datetime import datetime
import json
class NewsAnalysisSystem:
def __init__(self, analyzer_type='ml'):
"""
analyzer_type: 'dict' (사전), 'ml' (머신러닝), 'bert' (딥러닝)
"""
self.crawler = NaverNewsCrawler()
if analyzer_type == 'dict':
self.analyzer = KoreanSentimentAnalyzer()
elif analyzer_type == 'ml':
self.analyzer = MLSentimentAnalyzer()
elif analyzer_type == 'bert':
self.analyzer = BERTSentimentAnalyzer()
self.results = []
def analyze_keyword(self, keyword, max_news=20):
"""키워드 관련 뉴스 수집 및 분석"""
print(f"'{keyword}' 관련 뉴스 수집 중...")
# 뉴스 수집
news_list = self.crawler.get_news_list(keyword, max_news)
print(f"{len(news_list)}개 뉴스 발견!")
# 각 뉴스 분석
for i, news in enumerate(news_list, 1):
print(f"\n[{i}/{len(news_list)}] 분석 중...")
# 본문 가져오기 (요약문으로 대체 가능)
content = news['summary']
if content:
# 감정 분석
sentiment_result = self.analyzer.predict(content)
# 결과 저장
result = {
'keyword': keyword,
'title': news['title'],
'press': news['press'],
'link': news['link'],
'content': content[:200], # 일부만 저장
'sentiment': sentiment_result['sentiment'],
'confidence': sentiment_result.get('confidence', 0),
'analyzed_at': datetime.now()
}
self.results.append(result)
print(f"제목: {news['title'][:50]}...")
print(f"감정: {sentiment_result['sentiment']} "
f"(신뢰도: {sentiment_result.get('confidence', 0):.1%})")
return self.results
def get_statistics(self):
"""분석 결과 통계"""
if not self.results:
return None
df = pd.DataFrame(self.results)
stats = {
'total_count': len(df),
'sentiment_distribution': df['sentiment'].value_counts().to_dict(),
'avg_confidence': df['confidence'].mean(),
'by_press': df.groupby('press')['sentiment'].value_counts().to_dict()
}
return stats
def save_results(self, filename='news_analysis_results.json'):
"""결과 저장"""
# datetime을 문자열로 변환
results_to_save = []
for result in self.results:
result_copy = result.copy()
result_copy['analyzed_at'] = result_copy['analyzed_at'].isoformat()
results_to_save.append(result_copy)
with open(filename, 'w', encoding='utf-8') as f:
json.dump(results_to_save, f, ensure_ascii=False, indent=2)
print(f"\n결과가 {filename}에 저장되었습니다!")
def print_summary(self):
"""결과 요약 출력"""
stats = self.get_statistics()
if not stats:
print("분석 결과가 없습니다.")
return
print("\n" + "="*80)
print("📊 분석 결과 요약")
print("="*80)
print(f"\n총 분석 기사 수: {stats['total_count']}개")
print(f"평균 신뢰도: {stats['avg_confidence']:.1%}")
print("\n감정 분포:")
for sentiment, count in stats['sentiment_distribution'].items():
percentage = (count / stats['total_count']) * 100
print(f" {sentiment}: {count}개 ({percentage:.1f}%)")
print("\n언론사별 감정 분포:")
for key, count in list(stats['by_press'].items())[:5]:
print(f" {key}: {count}개")
# 실전 사용 예시
system = NewsAnalysisSystem(analyzer_type='ml')
# 여러 키워드 분석
keywords = ['경제성장', '주식시장', '부동산']
for keyword in keywords:
system.analyze_keyword(keyword, max_news=10)
time.sleep(2) # 키워드 간 딜레이
# 결과 확인
system.print_summary()
system.save_results()
이 시스템으로 할 수 있는 것들:
✅ 특정 키워드 관련 뉴스 자동 수집
✅ 각 뉴스의 감정(긍정/부정/중립) 자동 분석
✅ 언론사별, 키워드별 감정 분포 통계
✅ 결과를 JSON 파일로 저장하여 추가 분석 가능
📈 실전 활용 사례
이런 감정 분석 시스템을 어디에 쓸 수 있을까?실제 활용 사례들을 살펴보자! 🔍
1. 주식 투자 보조 도구 📊
class StockSentimentTracker:
def __init__(self):
self.analysis_system = NewsAnalysisSystem(analyzer_type='bert')
def track_company(self, company_name, days=7):
"""특정 기업 관련 뉴스 감정 추적"""
keywords = [
f"{company_name} 실적",
f"{company_name} 주가",
f"{company_name} 전망"
]
results = []
for keyword in keywords:
news_results = self.analysis_system.analyze_keyword(keyword, max_news=15)
results.extend(news_results)
# 감정 점수 계산
positive_count = sum(1 for r in results if r['sentiment'] == '긍정')
negative_count = sum(1 for r in results if r['sentiment'] == '부정')
sentiment_score = (positive_count - negative_count) / len(results) if results else 0
return {
'company': company_name,
'sentiment_score': sentiment_score,
'positive_ratio': positive_count / len(results) if results else 0,
'total_news': len(results),
'recommendation': self.get_recommendation(sentiment_score)
}
def get_recommendation(self, score):
"""투자 의견 생성"""
if score > 0.3:
return "긍정적 신호 - 관심 종목으로 모니터링"
elif score < -0.3:
return "부정적 신호 - 주의 필요"
else:
return "중립 - 추가 정보 필요"
# 사용 예시
tracker = StockSentimentTracker()
result = tracker.track_company("삼성전자")
print(f"감정 점수: {result['sentiment_score']:.2f}")
print(f"투자 의견: {result['recommendation']}")
2. 브랜드 평판 모니터링 🏢
기업 입장에서는 자사 브랜드가 언론에서 어떻게 다뤄지는지 실시간으로 파악할 수 있어.부정적인 기사가 급증하면 즉시 대응할 수 있지!
3. 정치 여론 분석 🗳️
선거 시즌에 각 후보자나 정당에 대한 언론 보도 감정을 분석하면여론의 흐름을 파악하는 데 도움이 돼.
4. 경쟁사 분석 🎯
경쟁사 관련 뉴스의 감정을 분석하면시장에서의 위치나 평판 변화를 모니터링할 수 있어.
⚡ 성능 향상 꿀팁
감정 분석 시스템을 더 정확하고 빠르게 만드는 방법들을 알려줄게!1. 도메인 특화 감정 사전 구축 📖
뉴스 도메인에 특화된 감정 단어들을 추가하면 정확도가 올라가:# 경제 뉴스 특화 감정 사전
economic_positive = {
'호황', '상승', '증가', '성장', '개선', '회복', '활성화',
'확대', '급등', '호조', '선방', '견조', '양호', '개선세'
}
economic_negative = {
'불황', '하락', '감소', '침체', '악화', '위축', '둔화',
'축소', '급락', '부진', '저조', '우려', '악화세', '위기'
}
# 정치 뉴스 특화 감정 사전
political_positive = {
'합의', '협력', '화해', '통합', '발전', '개혁', '혁신',
'민주', '평화', '안정', '신뢰', '지지'
}
political_negative = {
'갈등', '대립', '분열', '혼란', '부패', '비리', '스캔들',
'독재', '전쟁', '불안', '불신', '반대'
}
2. 문맥 고려한 감정 분석 🧠
단순히 단어만 보지 말고 앞뒤 문맥을 함께 봐야 해:def context_aware_analysis(text):
"""문맥을 고려한 감정 분석"""
# 부정 표현 탐지
negation_words = ['않', '못', '없', '아니']
sentences = text.split('.')
results = []
for sentence in sentences:
words = sentence.split()
# 부정어 뒤의 긍정어는 부정으로 전환
has_negation = any(neg in sentence for neg in negation_words)
if has_negation:
# 감정 반전 로직
sentiment = reverse_sentiment(sentence)
else:
sentiment = normal_sentiment(sentence)
results.append(sentiment)
return aggregate_sentiments(results)
3. 앙상블 기법 활용 🎯
여러 모델의 결과를 조합하면 더 정확해져:class EnsembleSentimentAnalyzer:
def __init__(self):
self.dict_analyzer = KoreanSentimentAnalyzer()
self.ml_analyzer = MLSentimentAnalyzer()
self.bert_analyzer = BERTSentimentAnalyzer()
def predict(self, text):
"""앙상블 예측"""
# 각 모델의 예측
dict_result = self.dict_analyzer.analyze(text)
ml_result = self.ml_analyzer.predict(text)
bert_result = self.bert_analyzer.predict(text)
# 가중 평균 (BERT에 더 높은 가중치)
weights = {
'dict': 0.2,
'ml': 0.3,
'bert': 0.5
}
# 점수 통합
final_score = (
dict_result['score'] * weights['dict'] +
ml_result['confidence'] * weights['ml'] +
bert_result['confidence'] * weights['bert']
)
return {
'sentiment': self.score_to_sentiment(final_score),
'confidence': abs(final_score),
'individual_results': {
'dict': dict_result,
'ml': ml_result,
'bert': bert_result
}
}
• 단일 모델의 오류를 보완
• 전반적인 정확도 향상
• 신뢰도 높은 예측 가능
4. 실시간 성능 모니터링 📊
class PerformanceMonitor:
def __init__(self):
self.predictions = []
self.execution_times = []
def log_prediction(self, text, result, execution_time):
"""예측 결과 로깅"""
self.predictions.append({
'text_length': len(text),
'sentiment': result['sentiment'],
'confidence': result['confidence'],
'execution_time': execution_time
})
self.execution_times.append(execution_time)
def get_statistics(self):
"""성능 통계"""
return {
'avg_execution_time': np.mean(self.execution_times),
'max_execution_time': np.max(self.execution_times),
'total_predictions': len(self.predictions),
'avg_confidence': np.mean([p['confidence'] for p in self.predictions])
}
def alert_if_slow(self, threshold=1.0):
"""느린 예측 알림"""
recent_times = self.execution_times[-10:]
if np.mean(recent_times) > threshold:
print(f"⚠️ 경고: 평균 실행 시간이 {threshold}초를 초과했습니다!")
🎨 시각화로 결과 표현하기
분석 결과를 예쁘게 시각화하면 훨씬 이해하기 쉬워져!matplotlib이나 plotly를 사용해보자 📈
import matplotlib.pyplot as plt
import matplotlib.font_manager as fm
from collections import Counter
# 한글 폰트 설정
plt.rcParams['font.family'] = 'Malgun Gothic' # Windows
# plt.rcParams['font.family'] = 'AppleGothic' # Mac
def visualize_sentiment_distribution(results):
"""감정 분포 파이 차트"""
sentiments = [r['sentiment'] for r in results]
sentiment_counts = Counter(sentiments)
colors = {
'긍정': '#66bb6a',
'부정': '#ef5350',
'중립': '#ffa726'
}
plt.figure(figsize=(10, 6))
plt.pie(
sentiment_counts.values(),
labels=sentiment_counts.keys(),
autopct='%1.1f%%',
colors=[colors.get(s, '#999') for s in sentiment_counts.keys()],
startangle=90
)
plt.title('뉴스 감정 분포', fontsize=16, fontweight='bold')
plt.axis('equal')
plt.show()
def visualize_timeline(results):
"""시간대별 감정 변화"""
df = pd.DataFrame(results)
df['date'] = pd.to_datetime(df['analyzed_at']).dt.date
daily_sentiment = df.groupby(['date', 'sentiment']).size().unstack(fill_value=0)
plt.figure(figsize=(14, 6))
daily_sentiment.plot(kind='bar', stacked=True,
color=['#66bb6a', '#ffa726', '#ef5350'])
plt.title('일별 감정 분포 변화', fontsize=16, fontweight='bold')
plt.xlabel('날짜')
plt.ylabel('기사 수')
plt.legend(title='감정')
plt.xticks(rotation=45)
plt.tight_layout()
plt.show()
def visualize_press_comparison(results):
"""언론사별 감정 비교"""
df = pd.DataFrame(results)
press_sentiment = pd.crosstab(df['press'], df['sentiment'])
plt.figure(figsize=(12, 6))
press_sentiment.plot(kind='barh', stacked=False,
color=['#66bb6a', '#ffa726', '#ef5350'])
plt.title('언론사별 감정 분포', fontsize=16, fontweight='bold')
plt.xlabel('기사 수')
plt.ylabel('언론사')
plt.legend(title='감정')
plt.tight_layout()
plt.show()
# 워드클라우드로 주요 키워드 시각화
from wordcloud import WordCloud
def create_sentiment_wordcloud(results, sentiment_type='긍정'):
"""감정별 워드클라우드"""
# 해당 감정의 기사들만 필터링
filtered = [r for r in results if r['sentiment'] == sentiment_type]
# 모든 텍스트 합치기
text = ' '.join([r['content'] for r in filtered])
# 워드클라우드 생성
wordcloud = WordCloud(
font_path='malgun.ttf', # 한글 폰트 경로
width=800,
height=400,
background_color='white',
colormap='RdYlGn' if sentiment_type == '긍정' else 'RdYlBu_r'
).generate(text)
plt.figure(figsize=(12, 6))
plt.imshow(wordcloud, interpolation='bilinear')
plt.axis('off')
plt.title(f'{sentiment_type} 뉴스 주요 키워드', fontsize=16, fontweight='bold')
plt.tight_layout()
plt.show()
이런 시각화를 추가하면 분석 결과를 보고서로 만들기도 좋고,프레젠테이션할 때도 훨씬 임팩트 있어! 🎉
🚨 주의해야 할 함정들
감정 분석을 하다 보면 빠지기 쉬운 함정들이 있어.미리 알고 있으면 실수를 줄일 수 있지! ⚠️
→ 겉으로는 긍정 단어지만 실제로는 부정적 의미
해결책: 문맥 분석, 구두점 패턴 분석, 고급 딥러닝 모델 사용
"주가가 놀랍게도 급등했다" ← 감정 포함
해결책: 주관성(subjectivity) 점수도 함께 고려
"공격적인 태도" ← 일반적으로는 부정적
해결책: 도메인별로 별도 모델 학습
해결책: 다양한 출처의 균형잡힌 데이터 수집
실전 디버깅 팁 🔧
def debug_prediction(text, analyzer):
"""예측 결과 디버깅"""
result = analyzer.predict(text)
print("="*80)
print("🔍 디버깅 정보")
print("="*80)
print(f"\n원문: {text[:200]}...")
print(f"\n예측 결과: {result['sentiment']}")
print(f"신뢰도: {result['confidence']:.1%}")
# 토큰화 결과 확인
tokens = analyzer.tokenize(text)
print(f"\n토큰화: {tokens[:100]}...")
# 감정 단어 추출
positive_words = [w for w in tokens.split() if w in analyzer.positive_words]
negative_words = [w for w in tokens.split() if w in analyzer.negative_words]
print(f"\n감지된 긍정 단어: {positive_words}")
print(f"감지된 부정 단어: {negative_words}")
# 의심스러운 경우 플래그
if result['confidence'] < 0.6:
print("\n⚠️ 주의: 신뢰도가 낮습니다. 수동 검토 권장")
return result
🌐 실제 서비스 배포하기
이제 만든 시스템을 실제로 서비스로 배포해보자!Flask나 FastAPI를 사용하면 웹 API로 만들 수 있어 🚀
FastAPI로 REST API 만들기
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from typing import List, Optional
import uvicorn
app = FastAPI(title="뉴스 감정 분석 API")
# 전역 분석기 초기화
analyzer = NewsAnalysisSystem(analyzer_type='bert')
class NewsRequest(BaseModel):
text: str
url: Optional[str] = None
class NewsResponse(BaseModel):
sentiment: str
confidence: float
probabilities: dict
class KeywordRequest(BaseModel):
keyword: str
max_news: int = 10
@app.get("/")
async def root():
return {
"message": "뉴스 감정 분석 API",
"version": "1.0.0",
"endpoints": ["/analyze", "/analyze-keyword", "/health"]
}
@app.post("/analyze", response_model=NewsResponse)
async def analyze_news(request: NewsRequest):
"""단일 뉴스 분석"""
try:
result = analyzer.analyzer.predict(request.text)
return NewsResponse(
sentiment=result['sentiment'],
confidence=result['confidence'],
probabilities=result['probabilities']
)
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.post("/analyze-keyword")
async def analyze_keyword(request: KeywordRequest):
"""키워드 기반 뉴스 수집 및 분석"""
try:
results = analyzer.analyze_keyword(
request.keyword,
max_news=request.max_news
)
stats = analyzer.get_statistics()
return {
"keyword": request.keyword,
"total_analyzed": len(results),
"statistics": stats,
"results": results[:5] # 상위 5개만 반환
}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.get("/health")
async def health_check():
"""헬스 체크"""
return {"status": "healthy", "model_loaded": True}
if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", port=8000)
서버 실행:
python api.py단일 뉴스 분석:
curl -X POST "http://localhost:8000/analyze" -H "Content-Type: application/json" -d '{"text":"경제가 빠르게 성장하고 있습니다"}'키워드 분석:
curl -X POST "http://localhost:8000/analyze-keyword" -H "Content-Type: application/json" -d '{"keyword":"주식시장","max_news":10}'
Docker로 컨테이너화하기 🐳
# Dockerfile
FROM python:3.9-slim
WORKDIR /app
# 시스템 패키지 설치
RUN apt-get update && apt-get install -y \
default-jdk \
&& rm -rf /var/lib/apt/lists/*
# Python 패키지 설치
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
# 애플리케이션 코드 복사
COPY . .
# 포트 노출
EXPOSE 8000
# 실행
CMD ["uvicorn", "api:app", "--host", "0.0.0.0", "--port", "8000"]
# requirements.txt
fastapi==0.104.1
uvicorn==0.24.0
pydantic==2.5.0
transformers==4.35.0
torch==2.1.0
konlpy==0.6.0
beautifulsoup4==4.12.2
requests==2.31.0
pandas==2.1.3
numpy==1.26.2
scikit-learn==1.3.2
# Docker 빌드 및 실행
docker build -t news-sentiment-api .
docker run -p 8000:8000 news-sentiment-api
이제 어디서든 API를 호출해서 감정 분석을 할 수 있어! 😎
💰 수익화 아이디어
이런 기술을 배웠으면 돈도 벌어야지? ㅋㅋ실제로 활용할 수 있는 수익화 방법들을 알려줄게! 💸
1. SaaS 서비스 구축 🌐
월 구독료를 받는 감정 분석 서비스를 만들 수 있어:요금제 예시:
• 무료: 하루 10건 분석
• 베이직: 월 $29 - 하루 100건
• 프로: 월 $99 - 하루 1,000건
• 엔터프라이즈: 맞춤 견적 - 무제한
2. 기업 컨설팅 📊
기업의 브랜드 평판 관리 서비스를 제공할 수 있어:• 경쟁사 분석 리포트
• 위기 관리 모니터링
• 마케팅 캠페인 효과 측정
3. 데이터 판매 📈
분석한 데이터 자체를 판매:• 산업별 감정 트렌드 리포트
• 주식 투자 참고 데이터
• 정치 여론 분석 데이터
4. 재능 공유 플랫폼 활용 🎯
재능넷 같은 플랫폼에서 AI 개발 재능을 공유할 수도 있어!• 맞춤형 감정 분석 시스템 개발
• 기존 시스템에 AI 기능 추가
• 데이터 분석 및 시각화 서비스
실제로 이런 기술을 가진 개발자들의 수요가 엄청 많거든 😊
📚 더 공부하면 좋은 것들
여기까지 왔으면 기본은 다 배운 거야!더 깊이 공부하고 싶다면 이런 것들을 추천해 🎓
• 자연어 처리(NLP) 기본 개념
• 파이썬 데이터 분석 (pandas, numpy)
• 머신러닝 기초 (scikit-learn)
2단계: 심화 학습
• 딥러닝 프레임워크 (PyTorch, TensorFlow)
• Transformer 아키텍처 이해
• BERT, GPT 등 최신 모델 연구
3단계: 실전 프로젝트
• 실제 데이터로 모델 학습
• 서비스 배포 및 운영
• 성능 최적화 및 모니터링
4단계: 전문가 되기
• 논문 읽기 및 최신 트렌드 파악
• 오픈소스 기여
• 커뮤니티 활동 및 지식 공유
유용한 리소스 📖
온라인 강의:• Coursera - Natural Language Processing Specialization
• Fast.ai - Practical Deep Learning for Coders
• Stanford CS224N - NLP with Deep Learning
책:
• "밑바닥부터 시작하는 딥러닝 2" (한빛미디어)
• "자연어 처리 인 액션" (제이펍)
• "트랜스포머를 활용한 자연어 처리" (한빛미디어)
커뮤니티:
• GitHub - 오픈소스 프로젝트 참여
• Kaggle - 데이터 분석 경진대회
• Reddit r/MachineLearning - 최신 논문 토론
• 국내 AI 커뮤니티 (AI Hub, 모두의연구소 등)
🎬 마무리하며
와... 여기까지 읽었다면 진짜 대단해! 👏우리가 함께 배운 내용을 정리해볼게:
✅ 감정 분석의 기본 개념과 원리
✅ 파이썬으로 감정 분석기 구현하기
✅ 사전 기반 → 머신러닝 → 딥러닝 단계별 발전
✅ 실제 뉴스 크롤링 및 분석 시스템 구축
✅ 성능 향상 및 최적화 기법
✅ API 서비스화 및 배포
✅ 실전 활용 및 수익화 방법
처음부터 완벽한 시스템을 만들려고 하지 마.
간단한 사전 기반부터 시작해서 점진적으로 개선해나가는 게 좋아!
2. 데이터가 핵심
아무리 좋은 모델도 데이터가 나쁘면 소용없어.
양질의 학습 데이터 확보가 가장 중요해!
3. 실전 경험이 중요
이론만 공부하지 말고 직접 만들어봐.
실패하고 디버깅하면서 진짜 실력이 늘어!
4. 지속적인 학습
AI 분야는 정말 빠르게 발전해.
최신 트렌드를 계속 따라가는 게 중요해!
처음에는 어려워 보였던 것들도 하나씩 따라하다 보면
어느새 자신만의 감정 분석 시스템을 만들 수 있을 거야.
혹시 막히는 부분이 있거나 더 궁금한 게 있다면
개발자 커뮤니티에 질문하거나, 공식 문서를 참고해봐.
그리고 재능넷 같은 플랫폼에서 전문가의 도움을 받는 것도 좋은 방법이야! 😊
자, 이제 여러분 차례야!
직접 코드를 작성하고, 실험하고, 개선해나가면서
멋진 AI 프로젝트를 만들어봐! 🚀
화이팅! 💪✨
댓글 작성
이 글에 대한 여러분의 생각을 들려주세요
로그인이 필요합니다
댓글을 작성하려면 먼저 로그인해주세요.
댓글 0
지식인의 숲 - 지적 재산권 보호 고지
지적 재산권 보호 고지
- 저작권 및 소유권: 본 컨텐츠는 재능넷의 독점 AI 기술로 생성되었으며, 대한민국 저작권법 및 국제 저작권 협약에 의해 보호됩니다.
- AI 생성 컨텐츠의 법적 지위: 본 AI 생성 컨텐츠는 재능넷의 지적 창작물로 인정되며, 관련 법규에 따라 저작권 보호를 받습니다.
- 사용 제한: 재능넷의 명시적 서면 동의 없이 본 컨텐츠를 복제, 수정, 배포, 또는 상업적으로 활용하는 행위는 엄격히 금지됩니다.
- 데이터 수집 금지: 본 컨텐츠에 대한 무단 스크래핑, 크롤링, 및 자동화된 데이터 수집은 법적 제재의 대상이 됩니다.
- AI 학습 제한: 재능넷의 AI 생성 컨텐츠를 타 AI 모델 학습에 무단 사용하는 행위는 금지되며, 이는 지적 재산권 침해로 간주됩니다.
아직 댓글이 없습니다.