Python is used to measure the number of words in a text file,

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.