Python实现结巴分词统计高频中文词汇

代码

复制代码
 1 # 读取文件
 2 fn = open('youxi.txt', 'rt', encoding='utf-8')  # 打开文件
 3 string_data = fn.read()  # 读出整个文件
 4 fn.close()  # 关闭文件
 5 
 6 # 文本预处理
 7 pattern = re.compile(u'\t|\n|\.|-|:|;|\)|\(|\?|"')  # 定义正则表达式匹配模式
 8 string_data = re.sub(pattern, '', string_data)  # 将符合模式的字符去除
 9 
10 # 文本分词
11 seg_list_exact = jieba.cut(string_data, cut_all=False)  # 精确模式分词
12 object_list = []
13 
14 # 分词并去除停用词
15 remove_words = set()
16 fr = open('stopword.txt', encoding = 'UTF-8')
17 for word in fr:
18     remove_words.add(str(word).strip())
19 fr.close()
20 
21 for word in seg_list_exact:  # 循环读出每个分词
22     if word not in remove_words:  # 如果不在去除词库中
23         object_list.append(word)  # 分词追加到列表
24 
25 # 词频统计
26 word_counts = collections.Counter(object_list)  # 对分词做词频统计
27 word_counts_top10 = word_counts.most_common(100)  # 获取前100最高频的词
28 print(word_counts_top10)  # 输出检查
复制代码

需要引入的库

1 import re  # 正则表达式库
2 import collections  # 词频统计库
3 import numpy as np  # numpy数据处理库
4 import jieba  # 结巴分词

文件内容示例

 

处理结果示例(前100)

 

posted @   靠谱杨  阅读(748)  评论(0编辑  收藏  举报
编辑推荐:
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具

喜欢请打赏

扫描二维码打赏

了解更多

点击右上角即可分享
微信分享提示