開発環境
- OS X Mavericks - Apple(OS)
- Emacs (CUI)、BBEdit - Bare Bones Software, Inc. (GUI) (Text Editor)
- Python (プログラミング言語)
Head First Python (Paul Barry(著)、 O'Reilly Media )のChapter 4(Persistence: Saving data to files)、SHARPEN YOUR PENCIL(p.111)を解いてみる。
SHARPEN YOUR PENCIL(p.111)
コード(BBEdit)
sample111.py
#!/usr/bin/env python3 #-*- coding: utf-8 man = [] other = [] try: data = open('sketch.txt') 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 data.close() except IOError: print('The datafile is missing!') try: man_data = open('man_data.txt', 'w') other_data = open('other_data.txt', 'w') print(man, file=man_data) print(other, file=other_data) man_data.close() other_data.close() except IOError: print("Can't open files")
入出力結果(Terminal)
$ ./sample111.py $ cat man_data.txt ['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!'] $ cat other_data.txt ["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 コメント:
コメントを投稿