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

import pandas as pd
import matplotlib.pyplot as plt
from matplotlib import rcParams
from nltk.sentiment.vader import SentimentIntensityAnalyzer
import nltk

# matplotlib のデフォルトフォントを設定(日本語フォントの問題を回避)
rcParams['font.family'] = 'sans-serif'
rcParams['font.sans-serif'] = ['DejaVu Sans']

# NLTK のダウンロード
nltk.download('vader_lexicon')

def analyze_sentiment(file_path):
    """
    CSVファイルのテキストデータの感情分析を行い、結果をグラフとテキストで表示する。

    Args:
        file_path (str): CSVファイルのパス。
    """
    try:
        # CSVファイルの読み込み
        df = pd.read_csv(file_path)
    except FileNotFoundError:
        print(f"エラー:指定されたファイルが見つかりませんでした。ファイルパス: {file_path}")
        return

    # VADER Sentiment Analyzer の初期化
    sid = SentimentIntensityAnalyzer()

    # 感情スコアを計算する関数
    def calculate_sentiment_scores(text):
        return sid.polarity_scores(text)

    # テキストデータの感情スコアを計算
    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', 'Fear']
    values = [pos_mean, neg_mean, neu_mean, compound_mean, 0]  # 恐怖はゼロで初期化
    colors = ['gold', 'red', 'grey', 'blue', 'purple']

    fig, ax = plt.subplots(figsize=(10, 6))
    bars = ax.bar(labels, values, color=colors)

    # 各項目の数値を表示
    for bar, value in zip(bars, values):
        ax.text(bar.get_x() + bar.get_width() / 2, bar.get_height() + 0.01, f'{value:.2f}', ha='center', fontsize=12)

    # タイトルとラベルの設定
    ax.set_title('Emotion Analysis Results', fontsize=15)
    ax.set_xlabel('Emotion Category', fontsize=12)
    ax.set_ylabel('Score', fontsize=12)

    # 説明テキストを追加
    descriptions = [
        f"Positive (gold): Optimistic or positive emotion - {pos_mean:.2f}",
        f"Negative (red): Pessimistic or negative emotion - {neg_mean:.2f}",
        f"Neutral (grey): Neither particularly positive nor negative emotion - {neu_mean:.2f}",
        f"Compound (blue): Overall balance of emotions - {compound_mean:.2f}",
        "Fear (purple): Fear or anxiety - 0.00"
    ]
    description_text = "\n".join(descriptions)
    plt.figtext(0.5, -0.3, description_text, ha='center', fontsize=12, wrap=True)
    plt.show()

    # 感情分析結果の概要を表示
    sentiment_summary = f"""
    感情分析結果の概要:
    ポジティブ: {pos_mean:.2f}
    ネガティブ: {neg_mean:.2f}
    中立: {neu_mean:.2f}
    複合: {compound_mean:.2f}
    恐怖: 0.00
    """
    print(sentiment_summary)

# 実行例
analyze_sentiment('Untitled4.csv')

ライブラリのインポート

  • pandas: データ分析ライブラリ
  • matplotlib.pyplot: グラフ描画ライブラリ
  • rcParams: matplotlibの設定をカスタマイズするためのモジュール
  • SentimentIntensityAnalyzer: NLTKの感情分析ツール
  • Counter: 要素の出現回数をカウントするツール(ここでは使用されていません)

CSVファイル名を入力する場所は、コードの最後の行にあるanalyze_sentiment()関数の引数です。

Python

# 実行例
analyze_sentiment('Untitled4.csv')

この例では、'Untitled4.csv'がCSVファイル名です。この部分を、分析したいCSVファイルの実際のファイル名に置き換えてください。

例:

  • data.csvというファイルを使用する場合:

analyze_sentiment(‘data.csv’)

  • my_data.csvというファイルを使用する場合:

analyze_sentiment(‘my_data.csv’)

⚠️英語Text用

コメント

コメントを残す

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

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

CAPTCHA

試行錯誤