2014年6月6日金曜日

開発環境

Head First Python (Paul Barry(著)、 O'Reilly Media )のChapter 4(Persistence: Saving data to files)、SHARPEN YOUR PENCIL(p.133)を解いてみる。

SHARPEN YOUR PENCIL(p.133)

コード(BBEdit)

sample133.py

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

import pickle

man = []
other = []
try:
    with open('sketch.txt') as data:
        for each_line in data:
            try:
                (role, line_spoken) = each_line.split(':', 1)
                line_spoken = line_spoken.strip()
                if role == 'Man':
                    man.append(line_spoken)
                elif role == 'Other Man':
                    other.append(line_spoken)

            except ValueError:
                pass
except IOError:
    print('The datafile is missing!')

try:
    with open('man_data.txt', 'wb') as man_file, \
         open('other_data.txt', 'wb') as other_file:
        pickle.dump(man, man_file)
        pickle.dump(other, other_file)
except IOError as err:
    print(type(err), err, err.args)
except pickle.PickleError as err:
    print(type(err), err, err.args)

try:
    with open('man_data.txt', 'rb') as man_file, \
         open('other_data.txt', 'rb') as other_file:
        man = pickle.load(man_file)
        other = pickle.load(other_file)
        print(man)
        print(other)
except IOError as err:
    print('The datafile is missing!')
except pickle.PickleError as err:
    print(type(err), err, err.args)

入出力結果(Terminal)

 ./sample133.py
['Is this the right room for an argument?', "No you haven't!", 'When?', "No you didn't!", "You didn't!", 'You did not!', 'Ah! (taking out his wallet and paying) Just the five minutes.', 'You most certainly did not!', "Oh no you didn't!", "Oh no you didn't!", "Oh look, this isn't an argument!", "No it isn't!", "It's just contradiction!", 'It IS!', 'You just contradicted me!', 'You DID!', 'You did just then!', '(exasperated) Oh, this is futile!!', 'Yes it is!']
["I've told you once.", 'Yes I have.', 'Just now.', 'Yes I did!', "I'm telling you, I did!", "Oh I'm sorry, is this a five minute argument, or the full half hour?", 'Just the five minutes. Thank you.', 'Anyway, I did.', "Now let's get one thing quite clear: I most definitely told you!", 'Oh yes I did!', 'Oh yes I did!', 'Yes it is!', "No it isn't!", 'It is NOT!', "No I didn't!", 'No no no!', 'Nonsense!', "No it isn't!"]
$

0 コメント:

コメントを投稿