自制多功能词云图生成程序——多文件分析、删除关键词等

前言

一直以来很喜欢词云图,能够很直观地体现文本的关键词,无奈技术有限,现使用AI写出了比较完整、功能强大的词图,分享给大家。
可以先看下成果,这是使用脚本生成的由chinese-poetry/chinese-poetry中宋词的词云图。

1771036336628.png

运行环境

系统环境:
1771036543649.png
安装:

1
pip3 install jieba wordcloud matplotlib

需要的文件:

常见停用词表来源说明:

根据中文自然语言处理(NLP)任务的差异,可选择不同版本的词表:

  • 哈工大(HIT)停用词表:应用最广泛,包含约767个词,涵盖了大多数日常用语中的无意义词汇。
  • 百度停用词表:包含约1395 个词,对搜索引擎产生的冗余词过滤效果较好。
  • 四川大学(SCU)停用词表:包含约1208个词,在处理社交媒体和长文章时表现较稳健。

脚本文件

开源地址:

zhyong26/Mac_shells: Mac M1个人使用脚本

其中第24行的停用词表文件路径,可根据实际修改。

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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
#!/usr/bin/env python
# coding=utf-8
import jieba
from collections import Counter
from wordcloud import WordCloud
import matplotlib.pyplot as plt
import argparse
import os
import sys

def get_macos_font():
"""自动化获取 macOS 可用的中文字体路径"""
paths = [
"/System/Library/Fonts/STHeiti Light.ttc",
"/System/Library/Fonts/PingFang.ttc",
"/Library/Fonts/Arial Unicode.ttf",
"/System/Library/Fonts/Hiragino Sans GB.ttc"
]
for p in paths:
if os.path.exists(p):
return p
return None

def generate_combined_analysis(file_paths, font_path=None, stop_words_path="~/Project/Python_wordcloud/stopwords/scu_stopwords.txt", exclude_words=None, skip_top=0):
all_word_counts = Counter()
processed_files = 0

# 1. 停用词与排除词处理
filter_set = set()
if stop_words_path and os.path.exists(stop_words_path):
with open(stop_words_path, 'r', encoding='utf-8') as f:
filter_set.update([line.strip() for line in f.readlines() if line.strip()])
if exclude_words:
filter_set.update(exclude_words)

# 2. 文本处理
for file_path in file_paths:
if not os.path.exists(file_path):
print(f"跳过不存在的文件: {file_path}")
continue
try:
with open(file_path, 'r', encoding='utf-8') as f:
content = f.read()
if not content.strip(): continue
words = jieba.cut(content)
filtered = [w for w in words if len(w) > 1 and w not in filter_set]
all_word_counts.update(filtered)
processed_files += 1
except Exception as e:
print(f"读取文件 {file_path} 出错: {e}")

# 3. 数据校验与 Skip 逻辑
if not all_word_counts:
print("错误:未提取到任何有效关键词,请检查输入文件内容或编码。")
return

if skip_top > 0:
top_n = [item[0] for item in all_word_counts.most_common(skip_top)]
print(f"已跳过最高频词: {top_n}")
for w in top_n:
del all_word_counts[w]

if not all_word_counts:
print("错误:跳过高频词后,数据为空。")
return

# 4. 字体适配 (核心修复点)
final_font = font_path
if not final_font or not os.path.exists(final_font):
if sys.platform == "darwin": # macOS
final_font = get_macos_font()
elif sys.platform == "win32": # Windows
final_font = "C:/Windows/Fonts/simhei.ttf"

if not final_font or not os.path.exists(final_font):
print("错误:未找到有效的字体文件,请通过 --font 参数手动指定。")
return

# 5. 生成词云
try:
print(f"正在使用字体: {final_font}")
wc = WordCloud(
font_path=final_font,
background_color='white',
width=1000,
height=800,
max_words=150
)
wc.generate_from_frequencies(all_word_counts)

output_name = "analysis_result.png"
wc.to_file(output_name)
print(f"成功!处理文件: {processed_files} | 结果保存至: {os.path.abspath(output_name)}")

# 打印排名前10的词供校验
print("最终分析高频词 (Top 20):", all_word_counts.most_common(20))

except Exception as e:
print(f"词云生成失败,具体原因: {e}")

if __name__ == "__main__":
parser = argparse.ArgumentParser(description="多文件词频分析工具")
parser.add_argument("filenames", nargs='+', help="文件路径")
parser.add_argument("--font", help="手动指定字体路径")
parser.add_argument("--stop", help="停用词路径")
parser.add_argument("--exclude", "-e", nargs='*', help="排除特定词")
parser.add_argument("--skip_top", type=int, default=0, help="跳过前N个词")

args = parser.parse_args()
generate_combined_analysis(args.filenames, args.font, args.stop, args.exclude, args.skip_top)

使用说明

帮助文档:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
usage: get_word_cloud.py [-h] [--font FONT] [--stop STOP] [--exclude [EXCLUDE ...]] [--skip_top SKIP_TOP] filenames [filenames ...]

多文件词频分析工具

positional arguments:
filenames 文件路径

options:
-h, --help show this help message and exit
--font FONT 手动指定字体路径
--stop STOP 停用词路径
--exclude, -e [EXCLUDE ...]
排除特定词
--skip_top SKIP_TOP 跳过前N个词

如进行宋词的内容分析,根据实际关键词请问,去除不必要关键字,最终使用及输出如下:

1771037001191.png

其中get_wc命令即为脚本文件,为方便使用,设置了alias。

1
alias get_wc="~/Project/Python_wordcloud/.venv/bin/python3 ~/Project/Python_wordcloud/get_word_cloud.py"

转换为正常使用命令,即为:

1
python3 get_word_cloud.py *song* --skip_top 8 -e tags null

分析文件即为chinese poety中所有含有”song”的文件名。


AI 总结 (Qwen API)

生成时间: 2026-02-14 10:53:18

深度总结:

该文章介绍了一个自主开发、面向中文文本的多功能词云图生成工具,核心目标是提升文本关键词可视化分析的实用性与灵活性。不同于基础词云脚本,该项目具备显著的工程化特征:

  • 多文件批量处理能力:支持通配符(如 *song*)传入多个文本文件,自动合并词频统计,适用于大规模语料(如宋词全集);
  • 精细化文本过滤机制:集成停用词表(哈工大/百度等主流资源)、用户自定义排除词(--exclude)及高频词自动跳过(--skip_top),有效抑制“的”“了”“人”等无意义高频干扰项,提升语义代表性;
  • 跨平台字体智能适配:针对 macOS、Windows 系统预置常见中文字体路径,并支持手动指定,彻底解决 wordcloud 中文乱码/方块字问题——这是中文词云落地的关键技术瓶颈;
  • 鲁棒性设计:包含文件存在性校验、编码异常捕获、空内容防护、数据空值预警等生产级容错逻辑,保障非专业用户也能稳定运行;
  • 开源可扩展架构:代码结构清晰(模块化函数 + Argparse CLI),便于二次开发(如接入 TF-IDF 权重、情感加权、词性筛选等高级功能)。

整体体现了“小而美”的数字人文工具理念:以轻量 Python 脚本为载体,融合自然语言处理(jieba 分词)、数据聚合(Counter)、可视化(WordCloud + Matplotlib)与系统交互(跨平台字体探测),在学术分析、内容运营、教学演示等场景中具备直接复用价值。


核心关键词标签(3–5个):

#词云图 #中文分词 #停用词过滤 #跨平台字体适配 #多文件批量分析