Advertisement
Mars83

9-4

Oct 9th, 2011
856
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.    
  17.    Enter a file name: mbox.txt
  18. """
  19.  
  20. ''' Functions '''
  21. def enterFileName():
  22.     """
  23.    The user has to enter a filename.
  24.    Returns fileName
  25.    """
  26.     fileName = None
  27.     while fileName == None:
  28.         # Enter filename
  29.         try:
  30.             fileName = input("Enter the filename: ")
  31.         except:
  32.             print("Invalid input!")
  33.             continue
  34.     return fileName
  35.  
  36. ''' Main '''
  37. # Open file
  38. fileName = enterFileName()
  39. try:
  40.     fhand = open(fileName)
  41. except:
  42.     print("File not found!")
  43.     exit()
  44.  
  45. sender = dict()
  46. for line in fhand:
  47.     words = line.split()
  48.     # print('Debug:', words)
  49.     if len(words) >= 2 and words[0] == 'From':
  50.         sender[words[1]] = sender.get(words[1], 0) + 1
  51.  
  52. # Print-out
  53. for i in sender:
  54.     if sender[i] == max(sender.values()):
  55.         print(str(i) + " " + str(sender[i]))
  56.  
  57. # Close file
  58. try:
  59.     fhand.close()
  60. except:
  61.     exit()
  62.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement