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

10-2

By: Mars83 on Oct 9th, 2011  |  syntax: Python  |  size: 1.60 KB  |  hits: 43  |  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 10.2
  6.    This program counts the distribution of the hour of the day for each of the
  7.    messages. You can pull the hour from the “From” line by finding the time
  8.    string and then splitting that string into parts using the colon character.
  9.    Once you have accumulated the counts for each hour, print out the counts,
  10.    one per line, sorted by hour as shown below.
  11.    
  12.    Sample Execution:
  13.    python timeofday.py
  14.    Enter a file name: mbox-short.txt
  15.    04 3
  16.    06 1
  17.    07 1
  18.    09 2
  19.    10 3
  20.    11 6
  21.    14 1
  22.    15 2
  23.    16 4
  24.    17 2
  25.    18 1
  26.    19 1
  27. """
  28.  
  29. ''' Functions '''
  30. def enterFileName():
  31.     """
  32.    The user has to enter a filename.
  33.    Returns fileName
  34.    """
  35.     fileName = None
  36.     while fileName == None:
  37.         # Enter filename
  38.         try:
  39.             fileName = input("Enter the filename: ")
  40.         except:
  41.             print("Invalid input!")
  42.             continue
  43.     return fileName
  44.  
  45. ''' Main '''
  46. # Open file
  47. fileName = enterFileName()
  48. try:
  49.     fhand = open(fileName)
  50. except:
  51.     print("File not found!")
  52.     exit()
  53.  
  54. distribution = dict()
  55. for line in fhand:
  56.     words = line.split()
  57.     # print('Debug:', words)
  58.     if len(words) >= 6 and words[0] == 'From':
  59.         hour = words[5].split(':')[0]
  60.         distribution[hour] = distribution.get(hour, 0) + 1
  61.  
  62. # Print-out
  63. t = list()
  64. for key in distribution:
  65.     t.append((key, distribution[key]))
  66.     t.sort()
  67. for i in t:
  68.     print(i[0], i[1])
  69.  
  70. # Close file
  71. try:
  72.     fhand.close()
  73. except:
  74.     exit()
  75.