本文展示如何用 Python 脚本:
批量读取文件夹中的多篇中文文档;
用 jieba
分词并统计词频(过滤停用词与单字符);
将各文档词频输出为对应 Excel 文件;
是文本分析、内容审查、报告编写中的实用技巧。
import os
path = '主要业务'
files = [os.path.join(path, f) for f in os.listdir(path)]
使用标准库 os.listdir()
枚举目录中的文件;
生成包含所有待处理文件路径的列表,便于后续遍历读取。
import jieba
for file in files:
txt = open(file, "r", encoding="utf-8").read()
words = jieba.lcut(txt)
freq = {}
for w in words:
if len(w) == 1:
continue
freq[w] = freq.get(w, 0) + 1
stopWords = ["2019", "主要", "企业", "业务", "公司", "产品", "..."]
for w in stopWords:
freq.pop(w, None)
items = sorted(freq.items(), key=lambda x: x[1], reverse=True)
使用 jieba.lcut()
精准分词,是中文文本处理常用方案 pankti0919.medium.com+2thedataschool.co.uk+2stackoverflow.com+2gist.github.com+5breezegeography.wordpress.com+5m.php.cn+5;
自定义长度过滤与停用词列表,保障高频词的质量。
import pandas as pd
df = pd.DataFrame(items, columns=['词', '次数'])
basename = os.path.splitext(os.path.basename(file))[0]
df.to_excel(f"词频/{basename}.xlsx", index=False)
用 pandas.DataFrame
存储词频词典并导出;
stopWords
列表作用类似英文文本中的停用词过滤,使结果更有价值 stackoverflow.com。
jieba 分词:适合中文分词处理 pankti0919.medium.com+1thedataschool.co.uk+1;
词频排序:按次数降序排列,可配合 Counter
简化统计 m.php.cn+3stackoverflow.com+3gist.github.com+3;
停用词机制:过滤不具有语义价值的常见词,结果更精炼;
可扩展性:
可增加 jieba.analyse.extract_tags()
提取关键词与 tf-idf pankti0919.medium.com+2m.php.cn+2breezegeography.wordpress.com+2;
加入 HTML 或 GUI 操作;
将结果写入数据库或绘制词云图;
通过这个小脚本,你可以高效:
批处理多个文本文件;
自动清洗文本,统计高频词;
导出 Excel 结果,用于报告、分析或展示。
更多实用案例,代码,素材如下:
自取链接:https://pan.quark.cn/s/a46f30accea2
如果你希望下一步集成词云生成、分组对比分析,或英文与多语种混排文本处理,也可以继续告诉我,我可以为你定制更丰富的教程!