用Python找出文件中使用率最高的汉字
来源:互联网 发布:中国软件税务事业部 编辑:程序博客网 时间:2024/06/05 23:04
这是我初学Python时写的,为了简便,我并没在排序完后再去掉非中文字符,稍微会影响性能(大约增加了25%的时间)。
或者让行数更少(好囧的列表综合):
此外还可以引入with语句,这样只需一行就能获得异常安全性。
3者性能几乎一样,结果如下:
你还可以看看找出使用率最高的英文单词的方法。
# -*- coding: gbk -*-import codecsfrom time import timefrom operator import itemgetterdef top_words(filename, size=10, encoding='gbk'): count = {} for line in codecs.open(filename, 'r', encoding): for word in line: if u'\u4E00' <= word <= u'\u9FA5' or u'\uF900' <= word <= u'\uFA2D': count[word] = 1 + count.get(word, 0) top_words = sorted(count.iteritems(), key=itemgetter(1), reverse=True)[:size] print '\n'.join([u'%s : %s次' % (word, times) for word, times in top_words])begin = time()top_words('空之境界.txt')print '一共耗时 : %s秒' % (time()-begin)
如果想用上新方法,以及让join的可读性更高的话,这样也是可以的:
# -*- coding: gbk -*-import codecsfrom time import timefrom operator import itemgetterfrom heapq import nlargestdef top_words(filename, size=10, encoding='gbk'): count = {} for line in codecs.open(filename, 'r', encoding): for word in line: if u'\u4E00' <= word <= u'\u9FA5' or u'\uF900' <= word <= u'\uFA2D': count[word] = 1 + count.get(word, 0) top_words = nlargest(size, count.iteritems(), key=itemgetter(1)) for word, times in top_words: print u'%s : %s次' % (word, times)begin = time()top_words('空之境界.txt')print '一共耗时 : %s秒' % (time()-begin)
或者让行数更少(好囧的列表综合):
# -*- coding: gbk -*-import codecsfrom time import timefrom operator import itemgetterdef top_words(filename, size=10, encoding='gbk'): count = {} for word in [word for word in codecs.open(filename, 'r', encoding).read() if u'\u4E00' <= word <= u'\u9FA5' or u'\uF900' <= word <= u'\uFA2D']: count[word] = 1 + count.get(word, 0) top_words = sorted(count.iteritems(), key=itemgetter(1), reverse=True)[:size] print '\n'.join([u'%s : %s次' % (word, times) for word, times in top_words])begin = time()top_words('空之境界.txt')print '一共耗时 : %s秒' % (time()-begin)
此外还可以引入with语句,这样只需一行就能获得异常安全性。
3者性能几乎一样,结果如下:
的 : 17533次引入psyco模块的成绩:
是 : 8581次
不 : 6375次
我 : 6168次
了 : 5586次
一 : 5197次
这 : 4394次
在 : 4264次
有 : 4188次
人 : 4025次
一共耗时 : 0.5秒
的 : 17533次注:测试文件为778KB的GBK编码,40余万字。
是 : 8581次
不 : 6375次
我 : 6168次
了 : 5586次
一 : 5197次
这 : 4394次
在 : 4264次
有 : 4188次
人 : 4025次
一共耗时 : 0.280999898911秒
- 用Python找出文件中使用率最高的汉字
- python 从一系列字符串中,找出频率最高的字符串
- 找出文件中最高频率的前k个单词
- 英文写作中使用率最高的基本句式
- Vista中使用率最高的11条命令
- 英文写作中使用率最高的基本句式
- 英文写作中使用率最高的基本句式
- Vista中使用率最高的11条命令
- Github项目中使用率最高的Java/Ruby/JS库
- Github项目中使用率最高的Java/Ruby/JS库
- 查询Java中CPU使用率最高的线程
- 使用率最高的SQL语句
- 题目:海量数据处理,从大文件中找出频数最高的词
- 找出一个字符串中出现频率最高的字符
- 找出字符串中出现频率最高的字符
- 48.找出字符串中出现频率最高的字母
- 几条使用率最高的SQL语句
- 几条使用率最高的SQL语句
- Android重力感应 .
- BMP文件结构
- 利用PLSQL工具导入导出数据库 .
- Hough变换原理
- windows查找进程关闭进程
- 用Python找出文件中使用率最高的汉字
- js获得下拉框被selected的项的值
- ActionBar和Fragment结合ViewPager实现TabActivity
- 美团笔试题目
- openstack 阅读
- ORACLE的 SQL优化 .
- Ubuntu修改环境变量
- 编程名言
- 情感失忆的伤感空间日志_如果说回忆是甜蜜的