Python找出文件中使用率最高的漢字實例詳解
本文實例講述了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)
或者讓行數(shù)更少(好囧的列表綜合):
# -*- 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程序設計有所幫助。
相關文章
PyTorch中的參數(shù)類torch.nn.Parameter()詳解
這篇文章主要給大家介紹了關于PyTorch中torch.nn.Parameter()的相關資料,要內容包括基礎應用、實用技巧、原理機制等方面,文章通過實例介紹的非常詳細,需要的朋友可以參考下2022-02-02
安裝Python的web.py框架并從hello world開始編程
這篇文章主要介紹了安裝Python的web.py框架并從hello world開始編程,web.py的作者年輕的Aaron Swartz已經離世,緬懷大神,需要的朋友可以參考下2015-04-04
使用pymysql查詢數(shù)據庫,把結果保存為列表并獲取指定元素下標實例
這篇文章主要介紹了使用pymysql查詢數(shù)據庫,把結果保存為列表并獲取指定元素下標實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-05-05
Ubuntu中安裝指定Python版本方法詳解(理論上各版本通用)
現(xiàn)在基于linux的發(fā)行版本有很多,有centos,ubuntu等,一般基于linux的衍生系統(tǒng)至少都安裝了Python2版本,但是現(xiàn)在Python已經是3.x版本大行其道了,這篇文章主要給大家介紹了關于Ubuntu中安裝指定Python版本方法的相關資料,理論上各版本通用,需要的朋友可以參考下2023-06-06

