Python如何进行词频统计?3种方法教给你

前言
本文的文字及图片来源于网络,仅供学习、交流使用,不具有任何商业用途,如有问题请及时联系我们以作处理。

以下文章来源于快学Python ,作者小小明

Python爬虫、数据分析、网站开发等案例教程视频免费在线观看

https://space.bilibili.com/523606542

Python如何进行词频统计?3种方法教给你

在这里插入图片描述

数据准备

import jieba

with open("D:/hdfs/novels/天龙八部.txt", encoding="gb18030") as f:
    text = f.read()
with open('D:/hdfs/novels/names.txt', encoding="utf-8") as f:
    for line in f:
        if line.startswith("天龙八部"):
            names = next(f).split()
            break

for word in names:
    jieba.add_word(word)

#  加载停用词
with open("stoplist.txt", encoding="utf-8-sig") as f:
    stop_words = f.read().split()
stop_words.extend(['天龙八部', '\n', '\u3000', '目录', '一声', '之中', '只见'])
stop_words = set(stop_words)
all_words = [word for word in cut_word if len(word) > 1 and word not in stop_words]
print(len(all_words), all_words[:20])

结果:

216435 [‘天龙’, ‘释名’, ‘青衫’, ‘磊落’, ‘险峰’, ‘行玉壁’, ‘月华’, ‘明马’, ‘疾香’, ‘幽崖’, ‘高远’, ‘微步’, ‘生家’, ‘子弟’, ‘家院’, ‘计悔情’, ‘虎啸’, ‘龙吟’, ‘换巢’, ‘鸾凤’]
统计词频排名前N的词
原始字典自写代码统计:

wordcount = {}
for word in all_words:
    wordcount[word] = wordcount.get(word, 0)+1
sorted(wordcount.items(), key=lambda x: x[1], reverse=True)[:10]
 

结果:

Python如何进行词频统计?3种方法教给你

使用计数类进行词频统计:

from collections import Counter

wordcount = Counter(all_words)
wordcount.most_common(10)
 

结果:

Python如何进行词频统计?3种方法教给你

使用pandas进行词频统计:

pd.Series(all_words).value_counts().head(10)

结果:
在这里插入图片描述

Python如何进行词频统计?3种方法教给你

从上面的结果可以看到使用collections的Counter类来计数会更快一点,而且编码也最简单。

分词过程中直接统计词频
Pandas只能对已经分好的词统计词频,所以这里不再演示。上面的测试表示,Counter直接对列表进行计数比pyhton原生带快,但循环中的表现还未知,下面再继续测试一下。

首先使用原生API直接统计词频并排序:

%%time
wordcount = {}
for word in jieba.cut(text):
    if len(word) > 1 and word not in stop_words:
        wordcount[word] = wordcount.get(word, 0)+1
print(sorted(wordcount.items(), key=lambda x: x[1], reverse=True)[:10])

结果:

[(‘段誉’, 2496), (‘说道’, 2151), (‘虚竹’, 1633), (‘萧峰’, 1301), (‘武功’, 1095), (‘阿紫’, 922), (‘阿朱’, 904), (‘乔峰’, 900), (‘王语嫣’, 877), (‘慕容复’, 871)]
Wall time: 6.04 s

下面我们使用Counter统python基础教程计词频并排序:

%%time
wordcount = Counter()
for word in jieba.cut(text):
    if len(word) > 1 and word not in stop_words:
        wordcount[word] += 1
print(wordcount.most_common(10))

结果:

[(‘段誉’, 2496), (‘说道’, 2151), (‘虚竹’, 1633), (‘萧峰’, 1301), (‘武功’, 1095), (‘阿紫’, 922), (‘阿朱’, 904), (‘乔峰’, 900), (‘王语嫣’, 877), (‘慕容复’, 871)]
Wall time: 6.21 s

可以看到Counter在循环中计数时反而慢了一丁点,但由于Counter类整体性能更佳,编写起来简单,所以一般都用Counter进行统计计数。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值