python

超轻量级php框架startmvc

Python文本统计功能之西游记用字统计操作示例

更新时间:2020-06-01 17:36 作者:startmvc
本文实例讲述了Python文本统计功能之西游记用字统计操作。分享给大家供大家参考,具体如

本文实例讲述了Python文本统计功能之西游记用字统计操作。分享给大家供大家参考,具体如下:

一、数据

xyj.txt,《西游记》的文本,2.2MB

致敬吴承恩大师,4020行(段)

二、目标

统计《西游记》中:

1. 共出现了多少个不同的汉字; 2. 每个汉字出现了多少次; 3. 出现得最频繁的汉字有哪些。

三、涉及内容:

1. 读文件; 2. 字典的使用; 3. 字典的排序; 4. 写文件

四、效果

五、源代码


# coding:utf8
import sys
reload(sys)
sys.setdefaultencoding("utf8")
fr = open('xyj.txt', 'r')
characters = []
stat = {}
for line in fr:
 # 去掉每一行两边的空白
 line = line.strip()
 # 如果为空行则跳过该轮循环
 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:
 characters.append(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(stat.items(), key=lambda d:d[1], reverse=True)
fw = open('result.csv', 'w')
for item in stat:
 # 进行字符串拼接之前,需要将int转为str
 fw.write(item[0] + ',' + str(item[1]) + '\n')
fr.close()
fw.close()

PS:这里再为大家推荐2款非常方便的统计工具供大家参考:

在线字数统计工具: http://tools.jb51.net/code/zishutongji

在线字符统计与编辑工具: http://tools.jb51.net/code/char_tongji