天天看点

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')