2014年6月15日日曜日

開発環境

Head First Python (Paul Barry(著)、 O'Reilly Media )のChapter 5(Comprehending data: Work that data)、EXERCISE(p.169)を解いてみる。

EXERCISE(p.169)

コード(BBEdit)

sample169.py

#!/usr/bin/env python3
#-*- coding: utf-8 -*-

def sanitize(time_string):
    if '-' in time_string:
        spliter = '-'
    elif ':' in time_string:
        spliter = ':'
    else:
        return (time_string)
    (mins, secs) = time_string.split(spliter)
    return (mins + '.' + secs)

def getTimes(name):
    try:
        with open('{0}.txt'.format(name)) as f:
            data = f.readline()
        return data.strip().split(',')
    except Exception as err:
        print(type(err), err, err.args)
        return None

for name in ['kamimura', 'james', 'julie', 'mikey', 'sarah']:
    times = getTimes(name)
    if times:
        print('{0}: {1}'.format(
            name, sorted(set(sanitize(t) for t in times))[:3]))

入出力結果(Terminal)

$ ./sample169.py 
<class 'FileNotFoundError'> [Errno 2] No such file or directory: 'kamimura.txt' (2, 'No such file or directory')
james: ['2.01', '2.22', '2.34']
julie: ['2.11', '2.23', '2.59']
mikey: ['2.22', '2.38', '2.49']
sarah: ['2.18', '2.25', '2.39']
$

0 コメント:

コメントを投稿