Python is used to measure the number of words in a text file,
This example describes how to count the number of words in a text file in Python. We will share this with you for your reference. The details are as follows:
Counts the number of partial files, and obtains the files from the file.txt file in the current directory.
#-*-Coding: GBK-*-import stringimport sysreload (sys) def compareItems (w1, c1), (w2, c2): if c1> c2: return-1 elif c1 = c2: return cmp (w1, w2) else: return 1def main (): fname = "file.txt" try: text = open (fname, 'R '). read () text = string. lower (text) failed T: 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 input top words to be counted:") items = counts. items () items. sort (compareItems) max = len (items) print "\ n total words:" + str (len (words) print "net number of words (de-duplicated ): "+ str (max) print" \ n "if n> max: n = max for I in range (n ): print "%-10 s % 5d" % items [I] if _ name _ = '_ main _': main ()
PS: here we recommend two very convenient statistical tools for your reference:
Online word count statistics tools:
Http://tools.jb51.net/code/zishutongji
Online character statistics and editing tools:
Http://tools.jb51.net/code/char_tongji