29:文件2

文件分割:将文件record.txt打开,用':'对每行进行分割,用'======'对每段对话进行分割,分别存放为#分别保存到文件boy_1, girl_1, boy_2, girl_2, boy_3, girl_3中

代码:

def save_file(boy , girl, count):      #文件保存函数
    #分别保存到文件boy_1, girl_1, boy_2, girl_2, boy_3, girl_3,
    file_name_boy ='C:\\个人文件\\Python_Learning\\' + 'boy_'+str(count) + '.txt'
    file_name_girl ='C:\\个人文件\\Python_Learning\\' + '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
            (role, line_spoken) = each_line.split(':',1)
            if role == '小甲鱼':
                boy.append(line_spoken)
            if role== '小客服':
                girl.append(line_spoken)

        if each_line[:6] == '======':
            save_file(boy , girl, count)

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

    save_file(boy , girl, count)

    f.close()

#调用函数完成分割

split_file('C:\\个人文件\\Python_Learning\\record.txt')

猜你喜欢

转载自blog.csdn.net/weixin_41004521/article/details/81159559
29
今日推荐