Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #! /usr/bin/env python3.2
- # -*- coding: utf-8 -*-
- # main.py
- """ Task: Exercise 8.5
- Write a program to read through the mail box data and when you find line
- that starts with “From”, you will split the line into words using the split
- function. We are interested in who sent the message which is the second
- word on the From line.
- From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008
- You will parse the From line and print out the second word for each From
- line and then you will also count the number of From (not From:) lines and
- print out a count at the end.
- This is a sample good output with a few lines removed:
- python fromcount.py
- Enter a file name: mbox-short.txt
- stephen.marquard@uct.ac.za
- louis@media.berkeley.edu
- zqian@umich.edu
- [...some output removed...]
- ray@media.berkeley.edu
- cwen@iupui.edu
- cwen@iupui.edu
- cwen@iupui.edu
- There were 27 lines in the file with From as the first word
- """
- # test.txt is equal to mbox.txt, but added following 3 lines somewhere:
- """
- >>> The next line fails with the original code:
- From xyz
- >>> because of there are more than one, but less than two words...
- """
- ''' Functions '''
- def enterFileName():
- """
- The user has to enter a filename.
- Returns fileName
- """
- fileName = None
- while fileName == None:
- # Enter filename
- try:
- fileName = input("Enter the filename: ")
- except:
- print("Invalid input!")
- continue
- return fileName
- # End of enterFileName()
- ''' Main '''
- fileName = enterFileName()
- try:
- fhand = open(fileName)
- except IOError:
- print("No such file available!")
- exit()
- count = 0
- for line in fhand:
- words = line.split()
- # print('Debug:', words)
- if len(words) >= 2 and words[0] == 'From':
- try: # Additional guard
- print(words[1])
- count += 1
- except IndexError:
- continue
- print("There were " + str(count) +
- " lines in the file with From as the first word")
- try:
- fhand.close()
- except:
- exit()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement