一、实验目的

  1. 掌握 Python 结合 jieba 分词库实现中文文本分词的方法,理解自定义词典、停用词的作用。
  2. 学会使用 WordCloud 库绘制中文词云图,可视化文本高频关键词。
  3. 熟悉文件读取、字符串过滤、词频统计、结果输出的完整流程,完成简易文档智能审查程序。
  4. 解决 matplotlib 中文乱码问题,掌握中文字体配置方案。
    二、实验环境
    • 操作系统:Windows
    • 开发工具:IntelliJ IDEA
    • Python 版本:Python3.8 及以上
    • 依赖库:jieba、wordcloud、matplotlib
    • 项目文件结构
    DocAnalysisAgent
    ├─ docs # 存放待分析txt文本
    ├─ stopwords.txt # 停用词表
    ├─ user_dict.txt # 自定义分词词典
    └─ doc_agent.py # 主程序代码
    三、实验原理
  5. jieba 分词:基于前缀词典实现中文句子切分,支持导入自定义词典,识别专业词汇(如大模型、智能体);停用词用来过滤无实际意义助词(的、了、和等)。
  6. 词频统计:使用collections.Counter统计分词后词语出现次数,筛选 Top50 高频词。
  7. WordCloud 词云:根据词语频次设置字号大小,频次越高文字越大,直观展示文本核心主题。
  8. Matplotlib 绘图:展示词云图像,配置中文字体避免标题乱码。
  9. 文本过滤:正则表达式筛选纯中文词汇,过滤特殊符号、不可见字符,消除词云方框乱码。
    四、核心代码
import os
import re
import jieba
from collections import Counter
from wordcloud import WordCloud
import matplotlib.pyplot as plt

# 配置matplotlib中文字体,解决标题中文方框乱码
plt.rcParams['font.sans-serif'] = ['Microsoft YaHei']
plt.rcParams['axes.unicode_minus'] = False

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)
        print(f"✅ 已加载自定义词典:{user_dict}")

    # 加载停用词
    stopwords = set()
    if stopwords_file and os.path.exists(stopwords_file):
        with open(stopwords_file, 'r', encoding='utf-8') as f:
            stopwords = set([line.strip() for line in f if line.strip()])
        print(f"✅ 已加载停用词表:{stopwords_file}")
    else:
        stopwords = {"的", "了", "和", "在", "是", "我", "你", "他", "我们", "他们", "为", "以",
                     "等", "并", "对", "与"}
        print("⚠️ 使用内置默认停用词")

    all_words = []
    file_report = []

    # 判断文档文件夹是否存在
    if not os.path.isdir(folder_path):
        print(f"❌ 错误:文件夹 {folder_path} 不存在!")
        return

    # 遍历docs下所有txt文件
    for filename in os.listdir(folder_path):
        if filename.endswith(".txt"):
            file_path = os.path.join(folder_path, filename)
            try:
                with open(file_path, 'r', encoding='utf-8') as f:
                    text = f.read()
                # jieba精确分词
                words = jieba.lcut(text)
                # 过滤规则:词语长度>1、不在停用词、只保留纯中文
                filtered_words = [
                    w for w in words
                    if len(w) > 1
                    and w not in stopwords
                    and re.match(r'[\u4e00-\u9fa5]+', w)
                ]
                all_words.extend(filtered_words)

                # 统计单个文件Top10高频词
                file_counter = Counter(filtered_words)
                file_top10 = file_counter.most_common(10)
                file_report.append(f"【文件名:{filename}】\n文件Top10关键词:{file_top10}\n")
                print(f"✅ 成功处理文件: {filename}")
                print(f"   本文件有效词汇数量:{len(filtered_words)}")

            except Exception as e:
                print(f"❌ 处理文件{filename} 时发生错误: {e}")

    # 判断是否读取到有效词汇
    if not all_words:
        print("⚠️ 未提取到有效词汇,请检查文件路径或文档内容!")
        return

    # 全局Top50高频词统计
    word_counts = Counter(all_words)
    top_50_words = word_counts.most_common(50)
    print("\n=====全局 Top 50 高频词 =====")
    for word, cnt in top_50_words:
        print(f"{word}:{cnt}")

    # 输出词频报告report.txt
    report_content = "\n".join(file_report)
    report_content += f"\n=====全部文档合并Top50高频词=====\n{top_50_words}"
    with open("report.txt", "w", encoding="utf-8") as rf:
        rf.write(report_content)
    print("\n📄 文档汇总报告已保存:report.txt")

    # 生成词云
    wordcloud = WordCloud(
        font_path=font_path,
        width=1000,
        height=800,
        background_color='white',
        max_words=50,
        collocations=False
    )
    wordcloud.generate_from_frequencies(dict(top_50_words))

    # 展示词云图
    plt.figure(figsize=(10, 8))
    plt.imshow(wordcloud, interpolation='bilinear')
    plt.axis('off')
    plt.title("本地文档高频词云分析", fontsize=22)
    plt.show()

    # 保存图片
    output_image = "document_wordcloud.png"
    wordcloud.to_file(output_image)
    print(f"🖼️ 词云图片已保存至: {output_image}")


if __name__ == "__main__":
    DOC_FOLDER = "./docs"
    FONT = r"C:/Windows/Fonts/msyh.ttc"
    STOP_WORD_FILE = "./stopwords.txt"
    DICT_FILE = "./user_dict.txt"

    analyze_documents(
        folder_path=DOC_FOLDER,
        font_path=FONT,
        stopwords_file=STOP_WORD_FILE,
        user_dict=DICT_FILE
    )

五、实验截图
在这里插入图片描述
在这里插入图片描述
六、问题与解决

  1. 问题 1:运行提示 “未提取到有效词汇” 解决:检查 docs 文件夹内是否有 txt 文件、文件编码为 UTF-8、文本不是空内容;过滤规则会剔除单字词语。
  2. 问题 2:词云上方出现方框乱码 解决:区分两处字体,WordCloud 自带 font_path,matplotlib 标题需要单独配置plt.rcParams;增加正则只保留中文,过滤特殊符号。
  3. 问题 3:pip 下载包很慢 解决:使用清华镜像源安装依赖。
    七、实验总结
    本次实验基于 jieba 分词实现中文文本解析,结合词云完成文档关键词可视化,实现简易本地文档审查。程序可以批量读取 txt 文档,通过自定义词典识别专业术语,停用词过滤无效助词,统计词频并生成报告与可视化图像。 实验过程中理解了中文分词难点,掌握 Python 文本处理、词云可视化、matplotlib 中文乱码的解决方法。该程序可以用于文章、笔记文本快速分析,直观把握文本核心内容。
Logo

有“AI”的1024 = 2048,欢迎大家加入2048 AI社区

更多推荐