Python 批量情感识别

代码

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
import os
import pandas as pd
from snownlp import SnowNLP
import matplotlib.pyplot as plt

def analyze_sentiment(text):
    """使用 SnowNLP 进行情感分析"""
    try:
        return SnowNLP(text).sentiments
    except:
        return None

def process_csv(file_path):
    """处理单个 CSV 文件"""
    try:
        df = pd.read_csv(file_path)
        if '评论内容' not in df.columns:
            print(f"文件 {file_path} 中没有'评论内容'列")
            return
        
        # 过滤空评论
        comments = df['评论内容'].dropna().tolist()
        if not comments:
            print(f"文件 {file_path} 中没有有效评论内容")
            return
        
        # 情感分析
        sentiments = []
        for comment in comments:
            score = analyze_sentiment(comment)
            if score is not None:
                sentiments.append(score)
        
        if not sentiments:
            print(f"文件 {file_path} 情感分析失败")
            return
        
        # 绘制图表
        plt.rcParams['font.sans-serif'] = ['SimHei']  # 设置中文字体
        plt.rcParams['axes.unicode_minus'] = False  # 解决负号显示问题
        plt.figure(figsize=(10, 6))
        plt.hist(sentiments, bins=20, color='skyblue', edgecolor='black')
        plt.title('评论情感分析分布')
        plt.xlabel('情感分数 (0-1)')
        plt.ylabel('评论数量')
        plt.grid(True, linestyle='--', alpha=0.7)
        
        # 保存图表
        output_path = os.path.join(os.path.dirname(file_path), 'sentiment_analysis.png')
        plt.savefig(output_path)
        plt.close()
        print(f"图表已保存到:{output_path}")
        
    except Exception as e:
        print(f"处理文件 {file_path} 时出错:{str(e)}")

def main():
    """主函数"""
    path = input("请输入要分析的目录路径:")
    if not os.path.isdir(path):
        print("路径不存在或不是目录")
        return
    
    # 递归查找 CSV 文件
    for root, _, files in os.walk(path):
        for file in files:
            if file.endswith('.csv'):
                file_path = os.path.join(root, file)
                print(f"正在处理文件:{file_path}")
                process_csv(file_path)

if __name__ == '__main__':
    main()

使用方法

输入要处理的目录路径,程序会自动处理目录下的所有 CSV 文件 (包含子目录),并将图表保存在同级目录下。

图表中数值越接近 1 则表示评论的情感越正向,越接近 0 则表示的情感越负向。