•任务:将文件(record.txt)中的数据进行分割并按照以下规律保存起来:
–小甲鱼的对话单独保存为boy_*.txt的文件(去掉“小甲鱼:”)
–小客服的对话单独保存为girl_*.txt的文件(去掉“小客服:”)
–文件中总共有三段对话,分别保存为boy_1.txt, girl_1.txt,boy_2.txt, girl_2.txt, boy_3.txt, gril_3.txt共6个文件(提示:文件中不同的对话间已经使用“==========”分割)
test1:
1 f = open("record.txt")
2
3 boy = []
4 girl = []
5 count = 1
6
7 for each_line in f:
8 if each_line[:6] != '======':#判断是否连续读到六个=
9 (role,line_spoken) = each_line.split(':',1)#split以:进行字符切割,
10 #将切得到的两部分内容依次存放在role与line_spoken中
11 if role == '小甲鱼':
12 boy.append(line_spoken)#将小甲鱼说的内容添加到列表boy中
13 if role == '小客服':
14 girl.append(line_spoken)#将小客服说的内容添加到列表girl中
15 else:
16 file_name_boy = 'boy_' + str(count) + '.txt'
17 file_name_girl = 'girl_' + str(count) + '.txt'
18
19 boy_file = open(file_name_boy,'w')#以w模式新建一个以file_name_boy命名的txt文件
20 girl_file = open(file_name_girl,'w')#并贴上boy_file的标签
21
22 boy_file.writelines(boy)#将列表boy中的内容写入到boy_file文件中
23 girl_file.writelines(girl)
24
25 boy_file.close()#关闭boy_file文件
26 girl_file.close()
27
28 boy = []#清空列表boy
29 girl = []
30 count += 1
31
32 file_name_boy = 'boy_' + str(count) + '.txt'
33 file_name_girl = 'girl_' + str(count) + '.txt'
34
35 boy_file = open(file_name_boy,'w')
36 girl_file = open(file_name_girl,'w')
37
38 boy_file.writelines(boy)
39 girl_file.writelines(girl)
40
41 boy_file.close()
42 girl_file.close()#记得关闭文件
test2:
1 def save_file(boy,girl,count):
2 file_name_boy = 'boy_' + str(count) + '.txt'
3 file_name_girl = 'girl_' + str(count) + '.txt'
4
5 boy_file = open(file_name_boy,'w')
6 girl_file = open(file_name_girl,'w')
7
8 boy_file.writelines(boy)
9 girl_file.writelines(girl)
10
11 boy_file.close()
12 girl_file.close()
13
14 def split_file(file_name):
15 f = open(file_name)
16
17 boy = []
18 girl = []
19 count = 1
20
21 for each_line in f:
22 if each_line[:6] != '======':
23 (role,line_spoken) = each_line.split(':',1)#split以:进行字符切割,
24 #将切得到的两部分内容依次存放在role与line_spoken中
25 if role == '小甲鱼':
26 boy.append(line_spoken)
27 if role == '小客服':
28 girl.append(line_spoken)
29 else:
30 save_file(boy,girl,count)
31
32 boy = []
33 girl = []
34 count += 1
35
36
37 save_file(boy,girl,count)
38 f.close()
39
40 split_file('record.txt')