課時29:文件:一個任務
阿新 • • 發佈:2018-08-20
line .com ole *** txt -s color class else
目錄:
一、一個任務
二、課時29課後習題及答案
****************
一、一個任務
****************
任務:將文件(record.txt)中的數據進行分割並按照以下規律保存起來:
(1)小甲魚的對話單獨保存為boy_*.txt的文件(去掉“小甲魚:”)
(2)小客服的對話單獨保存為girl_*.txt的文件(去掉“小客服:”)
(3)文件中總共有三段對話,分別保存為boy_1.txt, girl_1.txt,boy_2.txt, girl_2.txt, boy_3.txt, gril_3.txt共6個文件(提示:文件中不同的對話間已經使用“==========”分割)
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‘)
*******************************
二、課時29課後習題及答案
*******************************
課時29:文件:一個任務