Python實現統計文字檔案字數的方法

2022-09-27 10:42:08 字數 1181 閱讀 3996

統計文字檔案的字數,從當前目錄下的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, cwww.cppcns.comh, ' ')

words = string.split(text)

counts = {}

for w in words:

countwww.cppcns.coms[w] = counts.get(w,0) + 1

n = input("\n輸入要統計的top單詞數:")

items = counts.items()

items.sort(compareitems)

max = len(items)

print "\n單詞總計:" + str(len(words))

print "單詞淨個數(已去重):" + 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款非常方便的統計工具供大家參考使用:

**字數統計工具:

**字元統計與編輯工具:

Python實現大文字檔案分割

python 2 通過檔案拖拽或檔案路徑輸入,實現自定義大文字檔案分割。coding gbk import os,sys,shutil is file exits false while not is file exits files list if len sys.ar 1 print 請輸入要切...

python 讀寫文字檔案

本人最近新學python 用到文字檔案的讀取,經過一番研究,從網上查詢資料,經過測試,總結了一下讀取文字檔案的方法.a f open filename r content f.read decode utf 8 b f codecs.open encoding utf 8 content f.rea...

Python讀取文字檔案

給定c data hello.txt,內容如下 jack hello,how are you?rose i m good.按行讀取 filepath r c data hello.txt with open filepath as txtfile for line in txtfile print ...