您的位置:首页 > 编程语言 > Python开发

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

2014-06-17 16:54 841 查看
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!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐