用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_frequence[word] += 1 #如果存在,则将该单词对应键的值加一 else: word_frequence[word] = 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_frequence[words[i]] = word_frequence.get(words[i],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实现简单词频统计的问题,提出上述几个方面的知识和操作,通过亲自实验,证明该方法是有效的,本文使用这种方法解决了统计一本小说中某个人的名字,或者某个关键词在文章中出现的次数等问题,但方法并不简便,还有考虑不周的地方,未来可以继续研究更加简洁方便的代码进行处理。

相关推荐
会员源码网2 小时前
Python中生成器函数与普通函数的区别
python
Java水解3 小时前
Python开发从入门到精通:Web框架Django实战
后端·python
曲幽4 小时前
FastAPI + PostgreSQL 实战:给应用装上“缓存”和“日志”翅膀
redis·python·elasticsearch·postgresql·logging·fastapi·web·es·fastapi-cache
Lupino7 小时前
别再只聊 AI 写代码了:技术负责人要把“变更治理”提到第一优先级
python·docker·容器
Flittly9 小时前
【从零手写 ClaudeCode:learn-claude-code 项目实战笔记】(6)Context Compact (上下文压缩)
python·agent
曲幽19 小时前
FastAPI + PostgreSQL 实战:从入门到不踩坑,一次讲透
python·sql·postgresql·fastapi·web·postgres·db·asyncpg
用户8356290780511 天前
使用 C# 在 Excel 中创建数据透视表
后端·python
码路飞1 天前
FastMCP 实战:一个 .py 文件,给 Claude Code 装上 3 个超实用工具
python·ai编程·mcp
dev派1 天前
AI Agent 系统中的常用 Workflow 模式(2) Evaluator-Optimizer模式
python·langchain
前端付豪1 天前
AI 数学辅导老师项目构想和初始化
前端·后端·python