0 前言

本实验实现简易本地文档智能 Agent,批量读取文件夹 txt/md 文档;支持自定义词典、停用词;中文分词、过滤无效词汇,统计 Top50 高频词,输出词云图片 + CSV 关键词报告;处理文件异常、解决 wordcloud 中文方框乱码。体验 Vibe‑Coding:明确需求边界,分模块 AI 辅助开发。

1 需求说明

  1. 输入:文件夹路径(txt/md),可选自定义停用词、自定义专业词典。
  2. 处理:遍历文件→读取文本→jieba 精确分词→过滤停用词、过滤单字符词汇→统计词频。
  3. 输出:document_wordcloud.png词云图片;keyword_report.csv高频词汇总。
  4. 约束:捕获文件不存在、编码异常;必须配置中文字体,防止中文方框;没有有效词汇给出提示,程序不崩溃。

2 完整源代码

"""
代码思路(导包上方):
1. 加载配置:优先加载用户自定义jieba专业词典;读取停用词文件,如果文件不存在,使用程序内置基础停用词兜底;
2. 文件夹校验:判断输入文件夹是否真实存在;遍历目录,只读取后缀为txt、md的文档;
3. 文件读取:try‑except捕获单个文件编码错误、损坏;单个文件异常只跳过,不中断整个程序;
4. jieba.lcut精确模式分词;过滤条件:词语长度>1,词语不在停用词集合;收集全部有效词汇;
5. Counter统计全部词频,取出Top50高频词汇;写入csv报告保存词语与词频;
6. WordCloud生成词云,强制指定中文字体,设置尺寸1000*800,collocations=False关闭二元词组,避免重复;
7. matplotlib展示词云,同时保存PNG图片;
8. 防御逻辑:全部过滤后无有效词汇直接打印警告,终止后续绘图,避免报错。
"""
import os
import csv
import jieba
from collections import Counter
from wordcloud import WordCloud
import matplotlib.pyplot as plt

def analyze_documents(folder_path, font_path, stopwords_file=None, user_dict=None):
    # 加载自定义词典
    if user_dict and os.path.exists(user_dict):
        jieba.load_userdict(user_dict)

    stopwords = set()
    if stopwords_file and os.path.exists(stopwords_file):
        with open(stopwords_file, "r", encoding="utf‑8") as f:
            for line in f:
                w = line.strip()
                if w:
                    stopwords.add(w)
    else:
        stopwords = {"的", "了", "和", "在", "是", "我", "你", "他", "我们", "他们",
                     "为", "以", "等", "并", "对", "与", "这", "那", "也", "就"}

    valid_words_all = []
    if not os.path.isdir(folder_path):
        print(f"错误:文件夹 {folder_path} 不存在!")
        return

    for filename in os.listdir(folder_path):
        if filename.endswith((".txt", ".md")):
            full_path = os.path.join(folder_path, filename)
            try:
                with open(full_path, "r", encoding="utf‑8") as fp:
                    text = fp.read()
            except Exception as err:
                print(f"读取文件【{filename}】异常:{err},跳过该文件")
                continue
            words = jieba.lcut(text)
            valid = [w for w in words if len(w) > 1 and w not in stopwords]
            valid_words_all.extend(valid)

    if not valid_words_all:
        print("警告:没有提取任何有效词汇,请检查文档内容或停用词配置。")
        return

    counter = Counter(valid_words_all)
    top50 = counter.most_common(50)
    print("==== Top50高频词汇 ====")
    for word, cnt in top50:
        print(f"{word}:{cnt}")

    # 输出csv报告
    with open("keyword_report.csv", "w", encoding="utf‑8", newline="") as f:
        writer = csv.writer(f)
        writer.writerow(["词语", "词频"])
        writer.writerows(top50)
    print("关键词报告已保存 keyword_report.csv")

    # 生成词云
    wc = WordCloud(
        font_path=font_path,
        width=1000,
        height=800,
        background_color="white",
        max_words=50,
        collocations=False
    )
    wc.generate_from_frequencies(dict(top50))
    plt.figure(figsize=(10, 8))
    plt.imshow(wc, interpolation="bilinear")
    plt.axis("off")
    plt.title("本地文档高频词云分析", fontsize=16)
    plt.show()
    wc.to_file("document_wordcloud.png")
    print("词云图片保存完成 document_wordcloud.png")

if __name__ == "__main__":
    """
    Windows字体示例 msyh.ttc微软雅黑;simhei.ttf黑体
    准备:新建docs文件夹放入txt/md文本
    stopwords.txt、user_dict.txt每行一个词,UTF‑8编码,可省略
    """
    analyze_documents(
        folder_path="./docs",
        font_path="msyh.ttc",
        stopwords_file="stopwords.txt",
        user_dict="user_dict.txt"
    )

3 详细代码解析

  1. 导包os路径处理;csv输出报告;jieba中文分词;Counter统计词频;WordCloud词云;matplotlib.pyplot图片展示。
  2. 词典与停用词
  • jieba.load_userdict()加载专业词,提升专业文档分词准确度;
  • 如果停用词文件不存在,使用内置集合兜底,代码开箱可运行。
  1. 文件批量读取
  • 判断文件夹是否存在;只处理.txt、.md;
  • try‑except 捕获单文件异常,单个文件损坏不打断整体流程。
  1. 分词过滤jieba.lcut()精确模式;过滤条件len(w)>1剔除单字;过滤停用词。
  2. 词频统计与 CSV 输出Counter.most_common(50)取出出现最高 50 个词语;写入 csv 便于后续审查。
  3. WordCloud 关键参数font_path必须指定中文字体,否则中文方框;collocations=False关闭自动组合二元短语,避免重复垃圾词组;generate_from_frequencies()直接输入词频字典,效率更高。

4 安装依赖

pip install jieba wordcloud matplotlib numpy pillow

5 进阶拓展(博客结尾拓展阅读)

  1. 对接本地大模型,把高频词 + 文本片段送入 LLM 自动生成文档摘要审查意见;
  2. watchdog 库监控文件夹,新增文档自动触发分析;
  3. 结合蒙特卡洛做文档内概率指标模拟。

6 小结

该 Agent 完成文档文本层面的分析;Vibe‑Coding 不要一次性丢全部需求给 AI,按:文件读取→分词统计→词云绘图→异常处理分模块迭代开发,每一步运行验证。