本文实例讲述了Python文本统计功能之西游记用字统计操作。分享给大家供大家参考,具体如下:
一、数据
,《西游记》的文本,2.2MB
致敬吴承恩大师,4020行(段)
二、目标
统计《西游记》中:
1. 共出现了多少个不同的汉字;
2. 每个汉字出现了多少次;
3. 出现得最频繁的汉字有哪些。
三、涉及内容:
1. 读文件;
2. 字典的使用;
3. 字典的排序;
4. 写文件
四、效果
五、源代码
# coding:utf8
import sys
reload(sys)
("utf8")
fr = open('', 'r')
characters = []
stat = {}
for line in fr:
# 去掉每一行两边的空白
line = ()
# 如果为空行则跳过该轮循环
if len(line) == 0:
continue
# 将文本转为unicode,便于处理汉字
line = unicode(line)
# 遍历该行的每一个字
for x in xrange(0, len(line)):
# 去掉标点符号和空白符
if line[x] in [' ','', '\t', '\n', '。', ',', '(', ')', '(', ')', ':', '□', '?', '!', '《', '》', '、', ';', '“', '”', '……']:
continue
# 尚未记录在characters中
if not line[x] in characters:
(line[x])
# 尚未记录在stat中
if not stat.has_key(line[x]):
stat[line[x]] = 0
# 汉字出现次数加1
stat[line[x]] += 1
print len(characters)
print len(stat)
# lambda生成一个临时函数
# d表示字典的每一对键值对,d[0]为key,d[1]为value
# reverse为True表示降序排序
stat = sorted((), key=lambda d:d[1], reverse=True)
fw = open('', 'w')
for item in stat:
# 进行字符串拼接之前,需要将int转为str
(item[0] + ',' + str(item[1]) + '\n')
()
()
PS:这里再为大家推荐2款非常方便的统计工具供大家参考:
在线字数统计工具:http://tools./code/zishutongji
在线字符统计与编辑工具:http://tools./code/char_tongji
更多关于Python相关内容感兴趣的读者可查看本站专题:《Python文件与目录操作技巧汇总》、《Python文本文件操作技巧汇总》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》及《Python入门与进阶经典教程》
希望本文所述对大家Python程序设计有所帮助。
本文标题: Python文本统计功能之西游记用字统计操作示例
本文地址: /jiaoben/python/