brewersfan1976

ch5-ex2.py

Aug 6th, 2015
211
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.18 KB | None | 0 0
  1. # This program reads data from a sample text file
  2. # and prints out the number of capitalized words per
  3. # line in the file. We will use the sample file that
  4. # I generated in exercise 1.
  5. # In order for this program to work you need sample2CAP.txt
  6. # in the same directory as your program
  7.  
  8. # open file in read-only mode
  9.  
  10. # set line counter to 0
  11.  
  12. line_number = 0
  13.  
  14. # set capitalized words per line counter to 0
  15.  
  16. cap_words = 0
  17.  
  18. # open text file to read from
  19.  
  20. with open ("sample2CAP.txt", "r") as f:
  21.  
  22.      # read each line
  23.  
  24.      for line in f:
  25.  
  26.          # count the line number
  27.  
  28.          line_number = line_number + 1
  29.  
  30.          for w in line.split():
  31.  
  32.              # if the word is capitalized
  33.  
  34.              if (w.istitle() == True):
  35.  
  36.                 # count the number of capitalized words per line
  37.  
  38.                 cap_words = cap_words + 1
  39.  
  40.          # print the number of capitalized words per line
  41.        
  42.          print "Line ", line_number, ": ", cap_words, "capitalized word(s)"
  43.  
  44.          # reset the cap_words counter back to 0 to count the next line
  45.  
  46.          cap_words = 0
  47.  
  48. # we are all done. It is time to close the file and free up memory
  49.  
  50. f.close()
Advertisement
Add Comment
Please, Sign In to add comment