Python找出檔案中使用率最高的漢字例項詳解

2022-10-04 22:33:44 字數 2765 閱讀 1169

這是我初學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 &l程式設計客棧t;= 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)[:sizewww.cppcns.com]

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 wor程式設計客棧d, 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' o程式設計客棧r 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找出檔案中使用率最高的漢字例項詳解

本文位址: /jiaoben/python/125786.html

找出程式cpu使用率高的原因

確定是cpu過高 使用top觀察是否存在cpu使用率過高現象 找出執行緒 對cpu使用率過高的程序的所有執行緒進行排序 ps h e o pid,tid,pcpu,cmd sort pcpu grep 得到如下結果,其中執行緒2909使用了7.8 的cpu.2907 2913 0.0 2907 29...

找出程式cpu使用率高的原因

確定是cpu過高 使用top觀察是否存在cpu使用率過高現象 找出執行緒 對cpu使用率過高的程序的所有執行緒進行排序 ps h e o pid,tid,pcpu,cmd sort pcpu grep 得到如下結果,其中執行緒2909使用了7.8 的cpu.2907 2913 0.0 2907 29...

開發中,使用率較高的git命令總結

git remote add short name url git remote add 自己起的名字一般用 origin github遠端倉庫位址 git add 新增檔案到暫存區 git add readme.txt 提交某個檔案 git commit m 初始化專案版本 將暫存區內容新增到倉庫...