datafile.txt #文件
Man: this is the right room for an argument. Other Man: I've told you once. Man: No you haven't Other Man: Yes, I have. (pause) Man: When? Other Man: Just now. Man: No you didn't Other Man: Yes I did. Man: You didn't Other Man: I'm telling you, I did!
nester.py #输出模块 第2章文件nester.py修改后的模块,安装到你的python环境中
1 def print_lol(the_list, indent = False, level = 0, fn = sys.stdout): 2 for each_item in the_list: 3 if isinstance(each_item,list): 4 print_lol(each_item, indent, level + 1, fn); 5 else: 6 if indent: 7 for tab_stop in range(level): 8 print("\t",end='', file = fn) 9 print(each_item, file = fn)
sketch.py #读取文件datafile.txt, 去除两边空格, 存储到列表,从列表格式化(nester.py)后输出到文件man.out,other.out
1 import nester 2 man = [] 3 other = [] 4 try: 5 data = open ("datafile.txt") 6 7 for each_line in data: 8 try: 9 (role, line_spoken) = each_line.split(":", 1) 10 line_spoken = line_spoken.strip() 11 if role == 'Man': 12 man.append(line_spoken) 13 elif role == 'Other Man': 14 other.append(line_spoken) 15 16 except ValueError: 17 pass 18 19 data.close() 20 except IOError: 21 print('this data file is missing!') 22 23 try: 24 with open('man.out', 'w') as man_out, open('other.out','w') as other_out: 25 nester.print_lol(man, fn = man_out) 26 nester.print_lol(other, fn = other_out) 27 28 except fileError as err: 29 print('file error' + str(err))
man.out
this is the right room for an argument. No you haven't When? No you didn't You didn't
other.out
I've told you once. Yes, I have. Just now. Yes I did. I'm telling you, I did!