Advertisement
Mars83

9-4

Oct 9th, 2011
797
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.64 KB | None | 0 0
  1. #! /usr/bin/env python3.2
  2. # -*- coding: utf-8 -*-
  3.  
  4. # main.py
  5. """ Task: Exercise 9.4
  6.    Write a program to read through a mail log, and figure out who had the most
  7.    messages in the file. The program looks for “From” lines and takes the
  8.    second parameter on those lines as the person who sent the mail.
  9.    The program creates a Python dictionary that maps the sender’s address to
  10.    the total number of messages for that person.
  11.    After all the data has been read the program looks through the dictionary
  12.    using a maximum loop (see Section 5.7.2) to find who has the most messages
  13.    and how many messages the person has.
  14.    
  15.    Enter a file name: mbox-short.txt
  16.    cwen@iupui.edu 5
  17.    
  18.    Enter a file name: mbox.txt
  19.    zqian@umich.edu 195
  20. """
  21.  
  22. ''' Functions '''
  23. def enterFileName():
  24.     """
  25.    The user has to enter a filename.
  26.    Returns fileName
  27.    """
  28.     fileName = None
  29.     while fileName == None:
  30.         # Enter filename
  31.         try:
  32.             fileName = input("Enter the filename: ")
  33.         except:
  34.             print("Invalid input!")
  35.             continue
  36.     return fileName
  37.  
  38. ''' Main '''
  39. # Open file
  40. fileName = enterFileName()
  41. try:
  42.     fhand = open(fileName)
  43. except:
  44.     print("File not found!")
  45.     exit()
  46.  
  47. sender = dict()
  48. for line in fhand:
  49.     words = line.split()
  50.     # print('Debug:', words)
  51.     if len(words) >= 2 and words[0] == 'From':
  52.         sender[words[1]] = sender.get(words[1], 0) + 1
  53.  
  54. # Print-out
  55. for i in sender:
  56.     if sender[i] == max(sender.values()):
  57.         print(str(i) + " " + str(sender[i]))
  58.  
  59. # Close file
  60. try:
  61.     fhand.close()
  62. except:
  63.     exit()
  64.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement