assignment 10.2

统计出每条消息在一天中的小时分布。 从以“From”开头的行中, 找出时间字符串, 根据冒号将其分解。 对每个小时的次数进行累积, 按行打印出统计数, 并按照小时进行排序

代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
fhand = open('mbox-short.txt')
counts = dict()
for line in fhand:
if not line.startswith('From ') : continue
pieces = line.split()
time = pieces[5]
parts = time.split(':')
hour = parts[0]
counts[hour] = counts.get(hour,0) + 1
lst = list()
for key, val in sorted(counts.items()):
lst.append( (val, key) )


for val, key in lst[:] :
print key, val