課時29:檔案:一個任務

那是個好男孩發表於2018-08-20

目錄:

  一、一個任務

  二、課時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課後習題及答案

*******************************

 

相關文章