[record.txt](https://www.yuque.com/attachments/yuque/0/2022/txt/10367081/1644767218997-f31cac8c-ccb3-4d67-8495-28f10ae20bc2.txt?_lake_card=%7B%22src%22%3A%22https%3A%2F%2Fwww.yuque.com%2Fattachments%2Fyuque%2F0%2F2022%2Ftxt%2F10367081%2F1644767218997-f31cac8c-ccb3-4d67-8495-28f10ae20bc2.txt%22%2C%22name%22%3A%22record.txt%22%2C%22size%22%3A967%2C%22type%22%3A%22text%2Fplain%22%2C%22ext%22%3A%22txt%22%2C%22source%22%3A%22%22%2C%22status%22%3A%22done%22%2C%22mode%22%3A%22title%22%2C%22download%22%3Atrue%2C%22taskId%22%3A%22ud994d872-523a-4883-bd07-c47841eeb9e%22%2C%22taskType%22%3A%22upload%22%2C%22id%22%3A%22u5b7d886b%22%2C%22card%22%3A%22file%22%7D)<br />![image.png](https://cdn.nlark.com/yuque/0/2022/png/10367081/1644761839460-dde56ee2-9357-4dcb-9c81-fe238c6fe29c.png#clientId=u027d8d3c-4c8c-4&crop=0&crop=0&crop=1&crop=1&from=paste&height=349&id=u68da8376&margin=%5Bobject%20Object%5D&name=image.png&originHeight=528&originWidth=778&originalType=binary&ratio=1&rotation=0&showTitle=false&size=57715&status=done&style=none&taskId=u20f37a70-a7ac-4e6e-bcef-04fcac12200&title=&width=514)<br />任务:将文件(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个文件(提示:文件中不同的对话间已经使用 =======分割)
方式1
# 1.首先打开目标文件
f = open('record.txt')
print('结果:',f)
boy = []
girl = []
count = 1
# 2.获取一行的数据
# 3. 判断当前行是否有等号
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')
bb = boy_file.writelines(boy)
print('bb:', bb)
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')
bb = boy_file.writelines(boy)
print('bb:', bb)
girl_file.writelines(girl)
boy_file.close()
girl_file.close()
f.close()
方式2 (封装改良)
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(file_name)
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')