
10-2
By:
Mars83 on
Oct 9th, 2011 | syntax:
Python | size: 1.60 KB | hits: 43 | expires: Never
#! /usr/bin/env python3.2
# -*- coding: utf-8 -*-
# main.py
""" Task: Exercise 10.2
This program counts the distribution of the hour of the day for each of the
messages. You can pull the hour from the “From” line by finding the time
string and then splitting that string into parts using the colon character.
Once you have accumulated the counts for each hour, print out the counts,
one per line, sorted by hour as shown below.
Sample Execution:
python timeofday.py
Enter a file name: mbox-short.txt
04 3
06 1
07 1
09 2
10 3
11 6
14 1
15 2
16 4
17 2
18 1
19 1
"""
''' 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
''' Main '''
# Open file
fileName = enterFileName()
try:
fhand = open(fileName)
except:
print("File not found!")
exit()
distribution = dict()
for line in fhand:
words = line.split()
# print('Debug:', words)
if len(words) >= 6 and words[0] == 'From':
hour = words[5].split(':')[0]
distribution[hour] = distribution.get(hour, 0) + 1
# Print-out
t = list()
for key in distribution:
t.append((key, distribution[key]))
t.sort()
for i in t:
print(i[0], i[1])
# Close file
try:
fhand.close()
except:
exit()