天天看點

Python_檔案分割示例程式

#p107_分割檔案_更新版

#将JACK的對話單獨儲存為boy_.txt檔案(去掉“JACK”)

#将ROSE的對話單獨儲存為girl_.txt檔案(去掉“ROSE”)

#檔案中有4段對話,分别儲存為boy_1.txt、girl_1.txt、boy_2.txt、girl_2.txt……

#不同的對話已經用======分割

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):
    #字元串的分割
    count = 1
    boy = []
    girl = []

    f = open(file_name)

    for each_line in f:
        if each_line[:6] != '======':
            #字元串的分割
            (role, line_spoken) = each_line.split(':',1)
            if role == 'JACK':
                boy.append(line_spoken)
            if role == 'ROSE':
                girl.append(line_spoken)
        else:
            #檔案的分别儲存
            save_file(boy, girl, count)

            boy = []
            girl = []
            count += 1

    save_file(boy, girl, count)
    f.close()
    


    
split_file(r'C:\Users\Administrator\Desktop\示例\對話.txt')