Advertisement
Mars83

8-5

Oct 9th, 2011
1,032
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.16 KB | None | 0 0
  1. #! /usr/bin/env python3.2
  2. # -*- coding: utf-8 -*-
  3.  
  4. # main.py
  5. """ Task: Exercise 8.5
  6.    Write a program to read through the mail box data and when you find line
  7.    that starts with “From”, you will split the line into words using the split
  8.    function. We are interested in who sent the message which is the second
  9.    word on the From line.
  10.    
  11.    From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008
  12.    
  13.    You will parse the From line and print out the second word for each From
  14.    line and then you will also count the number of From (not From:) lines and
  15.    print out a count at the end.
  16.    This is a sample good output with a few lines removed:
  17.    
  18.    python fromcount.py
  19.    Enter a file name: mbox-short.txt
  20.    stephen.marquard@uct.ac.za
  21.    louis@media.berkeley.edu
  22.    zqian@umich.edu
  23.    
  24.    [...some output removed...]
  25.    
  26.    ray@media.berkeley.edu
  27.    cwen@iupui.edu
  28.    cwen@iupui.edu
  29.    cwen@iupui.edu
  30.    There were 27 lines in the file with From as the first word
  31. """
  32.  
  33. # test.txt is equal to mbox.txt, but added following 3 lines somewhere:
  34. """
  35. >>> The next line fails with the original code:
  36. From xyz
  37. >>> because of there are more than one, but less than two words...
  38. """
  39.  
  40. ''' Functions '''
  41. def enterFileName():
  42.     """
  43.    The user has to enter a filename.
  44.    Returns fileName
  45.    """
  46.     fileName = None
  47.     while fileName == None:
  48.         # Enter filename
  49.         try:
  50.             fileName = input("Enter the filename: ")
  51.         except:
  52.             print("Invalid input!")
  53.             continue
  54.     return fileName
  55. # End of enterFileName()
  56.  
  57. ''' Main '''
  58. fileName = enterFileName()
  59. try:
  60.     fhand = open(fileName)
  61. except IOError:
  62.     print("No such file available!")
  63.     exit()
  64. count = 0
  65. for line in fhand:
  66.     words = line.split()
  67.     # print('Debug:', words)
  68.     if len(words) >= 2 and words[0] == 'From':
  69.         try:                # Additional guard
  70.             print(words[1])
  71.             count += 1
  72.         except IndexError:
  73.             continue
  74. print("There were " + str(count) +
  75.       " lines in the file with From as the first word")
  76. try:
  77.     fhand.close()
  78. except:
  79.     exit()
  80.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement