温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Python中怎么实现词频统计功能

发布时间:2021-08-11 14:47:00 来源:亿速云 阅读:691 作者:Leah 栏目:大数据

这篇文章将为大家详细讲解有关Python中怎么实现词频统计功能,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。

数据准备

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]

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

from collections import Counter

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

结果:

Python中怎么实现词频统计功能

使用pandas进行词频统计:

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

分词过程中直接统计词频

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统计词频并排序:

%%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

关于Python中怎么实现词频统计功能就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI