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
import os
import pandas as pd
from wordcloud import WordCloud
import matplotlib.pyplot as plt
import jieba

def generate_wordcloud(text, save_path):
    # 中文分词
    seg_list = jieba.cut(text, cut_all=False)
    seg_text = " ".join(seg_list)
    
    # 生成词云
    wc = WordCloud(
        font_path='simhei.ttf',  # 中文字体
        background_color='white',
        width=800,
        height=600,
        max_words=200
    )
    wc.generate(seg_text)
    
    # 保存词云图
    plt.figure(figsize=(10, 8))
    plt.imshow(wc, interpolation='bilinear')
    plt.axis('off')
    plt.savefig(save_path, bbox_inches='tight', dpi=300)
    plt.close()

def process_csv_files(root_dir):
    for root, dirs, files in os.walk(root_dir):
        for file in files:
            if file.endswith('.csv'):
                csv_path = os.path.join(root, file)
                try:
                    df = pd.read_csv(csv_path)
                    
                    # 检查是否有"评论内容"列
                    if '评论内容' in df.columns:
                        # 过滤空内容
                        comments = df['评论内容'].dropna().tolist()
                        if comments:
                            text = " ".join(str(c) for c in comments)
                            output_path = os.path.join(root, f'wordcloud_{os.path.splitext(file)[0]}.png')
                            generate_wordcloud(text, output_path)
                            print(f"已生成词云图:{output_path}")
                except Exception as e:
                    print(f"处理文件 {csv_path} 时出错:{e}")

if __name__ == '__main__':
    input_path = input("请输入包含 CSV 文件的目录路径:")
    if os.path.isdir(input_path):
        process_csv_files(input_path)
    else:
        print("输入的路径无效,请检查后重试")

使用方法

直接粘贴文件夹绝对路径即可,会自动在子文件夹中查找 csv文件 并保存在同级文件夹下