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

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!

 

 

转载于:https://www.cnblogs.com/galoishelley/p/3793096.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值