python用字典统计单词或汉字词个数示例
时间:2021-09-02 17:14:10
有如下格式的文本文件
/“/请/!/”/“/请/!/”/两名/剑士/各自/倒转/剑尖/,/右手/握/剑柄/,
/左手/搭于/右手/手背/,/躬身行礼/。/两/人/身子/尚未/站/直/,
/突然/间/白光闪/动/,/跟着/铮的/一/声响/,
/双剑相/交/,/两/人/各/退一步/。
/旁/观众/人/都/是/“/咦/”/的/一声/轻呼/。/青衣/剑士/连/劈/三/剑/
将这段话进行词频统计,结果是 词—词数 的形式,比如 请 2 ,并把结果放到txt文件中。
这样的问题利用词或单词作为字典的key,循环判断有不有这个key,没有新增一个,有的话,将这个key对应的value加1
#coding:utf-8
word_lst = []
word_dict = {}
with open("中文.txt","r") as f1 ,open("词次数.txt",'w') as f2:
for line in f1:
word_lst.append(line.split('/'))
for item in word_lst:
for item2 in item:
if item2.strip() not in ",!。“”" :
if item2 not in word_dict:
word_dict[item2] = 1
else :
word_dict[item2] += 1
for key in word_dict:
print key,word_dict[key]
f2.write(key+' '+str(word_dict[key]))
标签:python,字典,统计
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
静态页面分页的AJAX实现
2008-01-19 16:19:00
![](https://img.aspxhome.com/file/UploadPic/20081/19/2008119162559319s.jpg)
pandas数据处理进阶详解
2023-04-15 03:40:33
Golang使用ini库读取配置详情
2023-07-02 07:46:56
![](https://img.aspxhome.com/file/2023/5/89035_0s.webp)
asp生成UTF-8格式的文件方法
2008-01-26 20:59:00
python编程进阶之类和对象用法实例分析
2022-04-01 23:59:03
用Dreamweaver MX制作文字特效
2011-06-14 09:49:47
![](https://img.aspxhome.com/file/UploadPic/20072/20072311216835s.gif)
python绘制分组对比柱状图
2021-01-03 06:48:26
![](https://img.aspxhome.com/file/2023/5/97335_0s.jpg)
利用Python网络爬虫爬取各大音乐评论的代码
2023-01-05 19:26:55
![](https://img.aspxhome.com/file/2023/6/95466_0s.png)
EasyASP v1.5发布(包含数据库操作类,原clsDbCtrl.asp)第1/2页
2011-04-08 10:40:00
Python学习之pip包管理工具的使用
2023-07-24 11:01:57
![](https://img.aspxhome.com/file/2023/9/97229_0s.png)
Python数据可视化之Seaborn的使用详解
2022-10-25 21:57:31
![](https://img.aspxhome.com/file/2023/2/89292_0s.png)
python脚本监控Tomcat服务器的方法
2023-10-03 18:19:23
![](https://img.aspxhome.com/file/2023/2/77042_0s.png)
如何用ASP发送HTML格式的邮件?
2010-06-11 19:41:00
Python网络编程之TCP套接字简单用法示例
2023-03-10 05:42:10
Python中注释(多行注释和单行注释)的用法实例
2023-07-04 15:05:01
python中字典增加和删除使用方法
2023-12-15 15:31:30
如何快速地更新网页内容?
2010-01-01 15:12:00
python flask框架实现重定向功能示例
2022-01-16 07:14:51
asp fso操作类
2011-03-07 10:57:00
python实现简单神经网络算法
2021-03-22 07:03:16
![](https://img.aspxhome.com/file/2023/9/97549_0s.jpg)