用Python字典简单实现词频统计

1 问题

在生活中我们偶尔会碰到一个任务要求:需要统计一本小说中某个人的名字,或者某个关键词在文章中出现的次数,由于字数太多我们不可能人为的慢慢去计数,这时我们可以根据程序来自动获得其次数。

2 方法

根据字典的性质,以此关键词或人名作为字典的键,出现次数作为其字典的值。首先对文中进行分词,对每个词建立键,以此遍历每个词。如果字典中有该词,则其值+1否则设为1并创建该词的键。

代码清单 1

|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| forexamle="You are you are,you are the trouble I'm in" forexample = forexamle.lower() words = forexample.split() word_frequence={} for word in words: if word in word_frequence.keys(): #判断当前访问的单词是否在字典中 word_frequenceword += 1 #如果存在,则将该单词对应键的值加一 else: word_frequenceword = 1 #如果不存在则创建键,并赋值为一 print(word_frequence) #get()实现 forexamle="You are you are,you are the trouble I'm in" forexample = forexamle.lower() words = forexample.split() word_frequence={} for i in range(len(words)): word_frequencewords\[i] = word_frequence.get(wordsi,0) + 1 #get()方法 如果取不到则为0; print(word_frequence) #内置库 from collections import Counter forexamle="You are you are,you are the trouble I'm in" forexample = forexamle.lower() words = forexample.split() print(dict(Counter(words))) |

3 结语

针对如何用python实现简单词频统计的问题,提出上述几个方面的知识和操作,通过亲自实验,证明该方法是有效的,本文使用这种方法解决了统计一本小说中某个人的名字,或者某个关键词在文章中出现的次数等问题,但方法并不简便,还有考虑不周的地方,未来可以继续研究更加简洁方便的代码进行处理。

相关推荐
Full Stack Developme4 分钟前
Java DFA算法
java·python·算法
techdashen13 分钟前
在 Fly.io 上使用 Rust 构建远程开发环境:从 Tokio 到 eBPF
开发语言·后端·rust
留白_17 分钟前
pandas文件读取与存储
开发语言·python·pandas
我的xiaodoujiao19 分钟前
API 接口自动化测试详细图文教程学习系列25--继续处理testCase中的数据
python·学习·测试工具·pytest
Wang ruoxi23 分钟前
Pygame 小游戏——节奏点击
python·pygame
夕除25 分钟前
AOP 实现 Redis 缓存切面解析
java·开发语言·python
fanjiu202031 分钟前
python查询nightingale监控
python
feifeigo12332 分钟前
马尔可夫决策过程(MDP)MATLAB 实现
开发语言·matlab
攻城狮Soar41 分钟前
STL源码解析之list(1)
开发语言·c++
TechWayfarer42 分钟前
IP画像在企业安全中的应用:它能做什么?不能替代什么
网络·python·tcp/ip·安全·网络安全