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.