黑松山资源网 Design By www.paidiu.com
本文实例讲述了Python找出文件中使用率最高的汉字的方法。分享给大家供大家参考。具体分析如下:
这是我初学Python时写的,为了简便,我并没在排序完后再去掉非中文字符,稍微会影响性能(大约增加了25%的时间)。
# -*- coding: gbk -*- import codecs from time import time from operator import itemgetter def 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 codecs from time import time from operator import itemgetter from heapq import nlargest def 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 codecs from time import time from operator import itemgetter def 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次 是 : 8581次 不 : 6375次 我 : 6168次 了 : 5586次 一 : 5197次 这 : 4394次 在 : 4264次 有 : 4188次 人 : 4025次 一共耗时 : 0.5秒
引入psyco模块的成绩:
的 : 17533次 是 : 8581次 不 : 6375次 我 : 6168次 了 : 5586次 一 : 5197次 这 : 4394次 在 : 4264次 有 : 4188次 人 : 4025次 一共耗时 : 0.280999898911秒
注:测试文件为778KB的GBK编码,40余万字。
希望本文所述对大家的Python程序设计有所帮助。
黑松山资源网 Design By www.paidiu.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
黑松山资源网 Design By www.paidiu.com
暂无评论...
更新日志
2024年10月09日
2024年10月09日
- 炉石传说最强战士卡组是哪个 战士最强天梯卡组推荐一览
- LexVandyke《HistoriadeunAmor情陷地中海》[WAV+CUE]
- TheBestPopClassics《LIGHTRHYTHMSOUND2》[WAV+CUE]
- TheLatinSoundofLexVandyke-ConciertodeAranjuez拉丁情人2012[SACD-ISO]
- 《怪物猎人世界》史低¥44,《耻辱终极版》仅需¥12
- 杉果秋促最后一天!海量3A大作击穿Steam史低
- 【果娘聊天室】国庆假期就这么水灵灵地结束啦!
- 《死或生》恋爱游戏新角色:来自大雷温柔公主的喂食
- 《寂静岭2》原制作人盛赞《寂静岭2:重制版》:新玩家能玩 我超高兴
- 艾什莉体模家今日份的COS:《鸣潮》守岸人 雪白香肩清纯而诱惑
- 微信积分商城进入方法,微信积分商城介绍
- 希诺宁进不进常驻说明,希诺宁角色分析
- 【原神】V5.0攻略 | 大型开图世界任务整合
- 群星.1990-细听锋芒(2014华星40金碟复刻版)【华星】【WAV+CUE】
- 郭婷筠.2024-爱你到底为啥物【福茂】【FLAC分轨】