[Head First Python]4.读取文件datafile.txt, 去除两边空格, 存储到列表,从列表格式化(nester.py)后输出到文件man.out,other.out

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环境中

 def print_lol(the_list, indent = False, level = 0, fn = sys.stdout):
for each_item in the_list:
if isinstance(each_item,list):
print_lol(each_item, indent, level + 1, fn);
else:
if indent:
for tab_stop in range(level):
print("\t",end='', file = fn)
print(each_item, file = fn)

sketch.py #读取文件datafile.txt, 去除两边空格, 存储到列表,从列表格式化(nester.py)后输出到文件man.out,other.out

 import nester
man = []
other = []
try:
data = open ("datafile.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('this data file is missing!') try:
with open('man.out', 'w') as man_out, open('other.out','w') as other_out:
nester.print_lol(man, fn = man_out)
nester.print_lol(other, fn = other_out) except fileError as err:
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!
上一篇:OC基础--OC中类的声明与定义


下一篇:Contains Duplicate 解答