Python statistical method for counting the number of words in a text file

Source: Internet
Author: User
The example in this article describes how the number of words in a Python statistical text file is. Share to everyone for your reference. The implementation method is as follows:

# count lines, sentences, and words of a text file# set all the counters to Zerolines, blanklines, sentences, words = 0, 0  , 0, 0print '-' * 50try: # Use a text file that has, or Google for this one ... filename = ' GettysburgAddress.txt ' TEXTF = Open (filename, ' r ') except Ioerror:print ' cannot open file%s for reading '% filename Import sys sys.exit (0) # reads one L Ine at a timefor line in Textf:print line, # test lines + = 1 if line.startswith (' \ n '): Blanklines + = 1 Else: # assume That's sentence ends with. or!  Or?  # so simply count these characters sentences + = Line.count ('. ') + line.count ('! ') + line.count ('? ') # Create a list of words # Use None to split at any whitespace regardless of the length # so for instance double space count s as one space tempwords = Line.split (None) Print tempwords # test # Word Total count words + = Len (tempwords) Textf.clo   SE () print '-' * 50print ' Lines: ", Linesprint" Blank Lines: ", blanklinesprint" sentences: ", Sentencesprint" Words :", words# optional console wait for Keypressfrom MSVCRT import Getchgetch () 

Hopefully this article will help you with Python programming.

  • 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.