Python實現(xiàn)統(tǒng)計文本文件字數(shù)的方法
本文實例講述了Python實現(xiàn)統(tǒng)計文本文件字數(shù)的方法。分享給大家供大家參考,具體如下:
統(tǒng)計文本文件的字數(shù),從當(dāng)前目錄下的file.txt取文件
# -*- coding: GBK -*-
import string
import sys
reload(sys)
def compareItems((w1,c1), (w2,c2)):
if c1 > c2:
return - 1
elif c1 == c2:
return cmp(w1, w2)
else:
return 1
def main():
fname = "file.txt"
try:
text = open(fname,'r').read()
text = string.lower(text)
except:
print "\nfile.txt is not exist!!! or There is a R/W error! "
sys.exit()
for ch in '!"#$%&()*+,-./:;<=>?@[\\]^_`{|}~':
text = string.replace(text, ch, ' ')
words = string.split(text)
counts = {}
for w in words:
counts[w] = counts.get(w,0) + 1
n = input("\n輸入要統(tǒng)計的top單詞數(shù):")
items = counts.items()
items.sort(compareItems)
max = len(items)
print "\n單詞總計:" + str(len(words))
print "單詞凈個數(shù)(已去重):" + str(max)
print "\n"
if n > max:
n = max
for i in range(n):
print "%-10s%5d" % items[i]
if __name__ == '__main__':
main()
PS:這里再為大家推薦2款非常方便的統(tǒng)計工具供大家參考使用:
在線字數(shù)統(tǒng)計工具:
http://tools.jb51.net/code/zishutongji
在線字符統(tǒng)計與編輯工具:
http://tools.jb51.net/code/char_tongji
更多關(guān)于Python相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Python文件與目錄操作技巧匯總》、《Python文本文件操作技巧匯總》、《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》及《Python入門與進階經(jīng)典教程》
希望本文所述對大家Python程序設(shè)計有所幫助。
相關(guān)文章
python利用requests庫模擬post請求時json的使用教程
這篇文章主要介紹了python利用requests庫模擬post請求時json的使用 ,本文給大家介紹的非常詳細,具有一定的參考借鑒價值,需要的朋友可以參考下2018-12-12
python實現(xiàn)文本界面網(wǎng)絡(luò)聊天室
這篇文章主要為大家詳細介紹了python實現(xiàn)文本界面網(wǎng)絡(luò)聊天室,具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-12-12
Python3+PyCharm+Django+Django REST framework配置與簡單開發(fā)教程
這篇文章主要介紹了Python3+PyCharm+Django+Django REST framework配置與簡單開發(fā)教程,需要的朋友可以參考下2021-02-02

