Don't like ads? PRO users don't see any ads ;-)
Guest

8-2

By: Mars83 on Oct 9th, 2011  |  syntax: Python  |  size: 1.22 KB  |  hits: 34  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. #! /usr/bin/env python3.2
  2. # -*- coding: utf-8 -*-
  3.  
  4. # main.py
  5. """ Task: Exercise 8.2
  6.    Figure out which line of the above program is still not properly guarded.
  7.    See if you can construct a text file which causes the program to fail and
  8.    then modify the program so that the line is properly guarded and test it
  9.    to make sure it handles your new text file.
  10. """
  11.  
  12. # test.txt is equal to mbox.txt, but added following 3 lines somewhere:
  13. """
  14. >>> The next line fails with the original code:
  15. From xyz
  16. >>> because of there are more than one, but less than two words...
  17. """
  18.  
  19. ''' Main '''
  20. try:
  21.     fhand = open('mbox.txt')
  22. except:
  23.     print("File not found!")
  24.     exit()
  25. week = ["Sat", "Sun", "Mon", "Tue", "Wed", "Fri"]
  26. count = 0
  27. for line in fhand:
  28.     words = line.split()
  29.     # print('Debug:', words)
  30.     if len(words) <= 2: continue    # when there are less than 3 words
  31.     if words[0] != 'From': continue
  32.     if words[2] not in week[:]: continue
  33.     try:                # Additional guard
  34.         print(words[2])
  35.         count += 1      # counts the interesting lines
  36.     except IndexError:
  37.         continue
  38. print("There are " + str(count) + " interesting lines.")
  39. try:
  40.     fhand.close()
  41. except:
  42.     exit()
  43.