テキスト感情分析(試作2)

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用

コメント

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です

コメントは日本語で入力してください。(スパム対策)

CAPTCHA

試行錯誤