python一键统计word文件中文词频

在学习过程中,掌握核心的概念非常重要,而哪些是核心的概念,一般重要的都会反复出现,所以,我们把需要学习的文档去统计出现频率最高的词汇,往往就是核心的概念。 下面就把如何把一篇word文档统计词汇的频率方法简单整理如下:

#使用jieba库进行中文分词,使用collections库中的Counter类统计词频,最后使用pandas库将结果输出到Excel文件。
import jieba
from collections import Counter
import pandas as pd
from docx import Document

# 读取word文件
def read_word(file_path):
    doc = Document(file_path)
    text = []
    for para in doc.paragraphs:
        text.append(para.text)
    return ' '.join(text)

# 分词并统计词频
def count_words(text):
    words = jieba.lcut(text)
    word_counts = Counter(words)
    return word_counts

# 将结果输出到Excel
def output_to_excel(word_counts, file_path):
    df = pd.DataFrame(list(word_counts.items()), columns=['词语', '出现次数'])
    df.to_excel(file_path, index=False)

# 主函数
def main():
    file_path_input=r'C:\Users\simaxiaohu\Desktop\11.docx'
    file_path_output=r'C:\Users\simaxiaohu\Desktop\统计结果.xlsx'
    text = read_word(file_path_input)
    word_counts = count_words(text)
    output_to_excel(word_counts, file_path_output)

if __name__ == '__main__':
    main()

其中file_path_input(需要统计的源文件)和file_path_output(统计结果输出的位置和文件名)根据自己的实际更改即可。

  • 8
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值