import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from matplotlib import rcParams
from nltk.sentiment.vader import SentimentIntensityAnalyzer
import nltk
from typing import List, Tuple
# matplotlib のデフォルトフォントを設定(日本語フォントの問題を回避)
rcParams['font.family'] = 'sans-serif'
rcParams['font.sans-serif'] = ['DejaVu Sans']
# NLTK のダウンロード
nltk.download('vader_lexicon')
def calculate_sentiment_scores(text: str) -> dict:
"""テキストの感情スコアを計算する。
Args:
text (str): 分析するテキスト。
Returns:
dict: 感情スコア(pos, neg, neu, compound)。
"""
sid = SentimentIntensityAnalyzer()
return sid.polarity_scores(text)
def create_radar_chart(labels: List[str], values: List[float], title: str):
"""レーダーチャートを作成する。
Args:
labels (List[str]): レーダーチャートのラベル。
values (List[float]): レーダーチャートの値。
title (str): レーダーチャートのタイトル。
"""
angles = np.linspace(0, 2 * np.pi, len(labels), endpoint=False).tolist()
angles += angles[:1]
values += values[:1]
fig, ax = plt.subplots(figsize=(8, 8), subplot_kw=dict(polar=True))
ax.fill(angles, values, color='blue', alpha=0.25)
ax.plot(angles, values, color='blue', linewidth=2)
ax.set_yticklabels([])
ax.set_xticks(angles[:-1])
ax.set_xticklabels(labels)
ax.set_title(title, size=20, color='blue', y=1.1)
plt.show()
def analyze_sentiment_from_csv(file_path: str) -> None:
"""CSVファイルから感情分析を行い、レーダーチャートを表示する。
Args:
file_path (str): CSVファイルのパス。
"""
try:
df = pd.read_csv(file_path)
except FileNotFoundError:
print(f"エラー:ファイル '{file_path}' が見つかりません。")
return
df['Scores'] = df['Text'].apply(calculate_sentiment_scores)
df = pd.concat([df.drop(['Scores'], axis=1), df['Scores'].apply(pd.Series)], axis=1)
pos_mean = df['pos'].mean()
neg_mean = df['neg'].mean()
neu_mean = df['neu'].mean()
compound_mean = df['compound'].mean()
labels = ['Positive', 'Negative', 'Neutral', 'Compound']
values = [pos_mean, neg_mean, neu_mean, compound_mean]
create_radar_chart(labels, values, 'Emotion Analysis Radar Chart')
if __name__ == "__main__":
analyze_sentiment_from_csv('Untitled1.csv')
ライブラリのインポート
pandas
: データ分析ライブラリmatplotlib.pyplot
: グラフ描画ライブラリrcParams
: matplotlibの設定をカスタマイズするためのモジュールSentimentIntensityAnalyzer
: NLTKの感情分析ツールCounter
: 要素の出現回数をカウントするツール(ここでは使用されていません)
CSVファイル名を入力する場所は、コードの最後の行にあるanalyze_sentiment()
関数の引数です。
Python
# 実行例
analyze_sentiment('Untitled1.csv')
この例では、'Untitled1.csv'
がCSVファイル名です。この部分を、分析したいCSVファイルの実際のファイル名に置き換えてください。
例:
data.csv
というファイルを使用する場合:
analyze_sentiment(‘data.csv’)
my_data.csv
というファイルを使用する場合:
analyze_sentiment(‘my_data.csv’)
⚠️英語Text用
コメントを残す