開発環境
- 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)、EXERCISE(p.127)を解いてみる。
EXERCISE(p.127)
コード(BBEdit)
kpnester.py
#!/usr/bin/env python3 #-*- coding: utf-8 -*- """ This is the nester.py module for nested (nested...) list. function(s) printLoL(list) """ import sys def printLoL(the_list, indent=False, level=0, file=sys.stdout): """ print each data in the list( and nested list) print each line """ for each_item in the_list: if isinstance(each_item, list): printLoL(each_item, indent, level+1, file=file) else: if indent: for tag_stop in range(level): print('\t', end='', file=file) print(each_item, file=file)
sample127.py
#!/usr/bin/env python3 #-*- coding: utf-8 -*- import kpnester 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', 'w') as man_file, \ open('other_data.txt', 'w') as other_file: kpnester.printLoL(man, file=man_file, indent=True, level=1) kpnester.printLoL(other, file=other_file, indent=True, level=2) except IOError as err: print('File error {0}'.format(err))
入出力結果(Terminal)
$ ./sample127.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 コメント:
コメントを投稿