根据视频自己练习
任务如下:
【理清思路】
1、 首先读取文件
2、 将文件存入列表逐行进行分析 :
如果没有到 分隔符 “” 标识 , 那就进行数据提取并分别存在boy 和gilr 列表中 ;
如果到了 分隔符 “” 标识 , 那就将已经分类的列表数据命名存储为文件 ;
3、 直到文件结束后 , 关闭文件 , 任务完成。
初稿代码如下 :
f = open('record.txt')
boy = []
girl = []
count = 1
for each_line in f:
if each_line[:6] != '======':
(role, line_spoken) = each_line.split(':', 1)
if role == '小甲鱼':
boy.append(line_spoken)
if role == '小客服':
girl.append(line_spoken)
else:
file_name_boy = 'boy_' + str(count) + '.txt'
file_name_girl = 'girl_' + str(count) + '.txt'
boy_file = open(file_name_boy, 'w')
girl_file = open(file_name_girl, 'w')
boy_file.writelines(boy)
girl_file.writelines(girl)
boy_file.close()
girl_file.close()
boy = []
girl = []
count += 1
file_name_boy = 'boy_' + str(count) + '.txt'
file_name_girl = 'girl_' + str(count) + '.txt'
boy_file = open(file_name_boy, 'w')
girl_file = open(file_name_girl, 'w')
boy_file.writelines(boy)
girl_file.writelines(girl)
boy_file.close()
girl_file.close()
f.close()
运行没有问题 , 但是不够专业 ,下面是 模块化的代码 :
def save_file(boy, girl, count):
file_name_boy = 'boy_' + str(count) + '.txt'
file_name_girl = 'girl_' + str(count) + '.txt'
boy_file = open(file_name_boy, 'w')
girl_file = open(file_name_girl, 'w')
boy_file.writelines(boy)
girl_file.writelines(girl)
boy_file.close()
girl_file.close()
def split_file(file_name):
f = open('record.txt')
boy = []
girl = []
count = 1
for each_line in f:
if each_line[:6] != '======':
(role, line_spoken) = each_line.split(':', 1)
if role == '小甲鱼':
boy.append(line_spoken)
if role == '小客服':
girl.append(line_spoken)
else:
save_file(boy, girl, count)
boy = []
girl = []
count += 1
save_file(boy, girl, count)
f.close()
split_file('record.txt')
这样就清晰多了 !
课后练习
def file_write(file_name):
f = open(file_name,'w')
print("输入 :w ,回车保存文件")
while True:
write_some = input()
if write_some != ':w':
f.write('%s\n' % write_some)
else:
break
f.close()
file_name = input('请输入文件名 : ')
file_write(file_name)