This article mainly describes the Python implementation of statistical text file Word Count method, involving Python for text file reading and string conversion, operation and other related operations skills, the need for friends can refer to the following
This paper describes how Python implements the word count of a statistical text file. Share to everyone for your reference, as follows:
Count the number of words in the text file, from the current directory of the File.txt to fetch files
#-*-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) 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: c OUNTS[W] = Counts.get (w,0) + 1 n = input ("\ n Enter the number of top words to Count:") items = Counts.items () Items.Sort ( Compareitems) max = len (items) print "\ n Words total:" + str (words) print "net number of words (removed):" + str (max) print "\ n" if n > Max: n = max for i in range (n): print "%-10s%5d"% items[i]if name = = ' main ':
main ()
"Recommended"
1. Special Recommendation: "PHP Programmer Toolkit" V0.1 version download
2. Python Free video tutorial
3. Python Basics Introductory Tutorial