博客
关于我
[整理] python统计词频
阅读量:434 次
发布时间:2019-03-06

本文共 1085 字,大约阅读时间需要 3 分钟。

简单的数据词频统计方法

在实际开发中,我们常需要对文本数据进行词频统计,这可以帮助我们快速了解文本中各个关键词的出现频率。本文将介绍两种常见的词频统计方法:一种适用于中文文本,另一种适用于英文文本。

中文词频统计

以下是实现中文词频统计的完整代码示例:

import stringtext = "http request highclient springboot request"data = text.lower().split()words = {}for word in data:    if word not in words:        words[word] = 1    else:        words[word] += 1result = sorted(words.items(), key=lambda x: x[1], reverse=True)print(result)

运行该代码,可得以下结果:

[('springboot', 1), ('request', 2), ('http', 1), ('highclient', 1)]

英文词频统计

以下是实现英文词频统计的完整代码示例,基于瓦登尔湖这本书籍:

import stringpath = 'D:/python3/Walden.txt'with open(path, 'r', encoding='utf-8') as text:    words = [raw_word.strip(string.punctuation).lower() for raw_word in text.read().split()]counts = {}for word in words:    counts[word] = counts.get(word, 0) + 1sorted_words = sorted(counts.items(), key=lambda x: x[1], reverse=True)for word, count in sorted_words:    print(f"{word} -- {count} times")

运行该代码,可得以下结果:

highclient -- 1 timethe -- 21 timesand -- 16 timesto -- 16 timesis -- 14 times... (以下其他词频统计结果)

以上代码和分析方法可以帮助我们快速统计不同语言文本中的关键词频率。在实际应用中,可以根据需要调整统计方式和排序规则。

转载地址:http://phcuz.baihongyu.com/

你可能感兴趣的文章
powershell常用
查看>>
PowerShell操作XML遇到的问题
查看>>
PowerShell攻击工具Empire实战
查看>>
PowerShell攻击工具Nishang实战
查看>>
PowerShell攻击工具PowerSploit实战
查看>>
Powershell管理系列(四)Lync server 2013 批量启用语音及分配分机号
查看>>
PowerShell脚本运行完 不要马上关闭用什么命令可以停留窗口窗口
查看>>
PowerShell远程连接到Windows
查看>>
power(8) identity
查看>>
POW的重力之美
查看>>
PO、VO、DAO、BO、DTO、POJO能分清吗?
查看>>
pytorch介绍-ChatGPT4o作答
查看>>
PP-PLL:基于概率传播的部分标签学习
查看>>
pytorch介绍
查看>>
pprint 排序字典但不是集合?
查看>>
pptp拨号上网
查看>>
ppt上的倒计时小工具_PPT中有哪些「看似很 LOW,实则惊艳」的小工具
查看>>
PPT添加视频的路径问题
查看>>
PPT美化插件 islide 安装过程问题“加载com加载项时运行出现错误”
查看>>
Prefix Tuning:详细解读Optimizing Continuous Prompts for Generation
查看>>