| 
 | 
 
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册  
 
x
 
f = open('D:\\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 
 
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 spilt_file(file_name): #传入文件名
 
 -         f = open(file_name,"r",encoding='UTF-8')
 
 -            #关键点,编码方式                   就这里换个编码形式
 
 -         boy=[]    
 
 -         girl=[]
 
 -         count=1    
 
 -             
 
 -         for each_line in f: #遍历原对话文件每一行
 
 -             if each_line[:6]!='======':  #以分割线判断
 
 -                 (role,line_spoken)=each_line.split(':',1)
 
 -                 #以:为界,分成元组,进行1次操作
 
 -                 if role =='小甲鱼': #根据名称(前三个字符)不同分别记入两个列表
 
 -                     boy.append(line_spoken)
 
 -                 if role =='小客服':
 
 -                     girl.append(line_spoken)
 
 -                     #到这一步,所有对话均被存入两列表
 
 -             else:  #不是分割线的情况下,写入
 
 -                 save_file(boy,girl,count) #调用写入,写入后清空列表,等待下次添加对话内容
 
 -                 
 
 -                 boy=[]
 
 -                 girl=[]
 
 -                 count+=1     #count从2到3时跳出循环,所以文件里计数器count为3的那一对文件就缺少了
 
 -             
 
 -         save_file(boy,girl,count)  #第三段内容(上方for循环漏掉一次写入)
 
 -         f.close()    
 
 -         
 
 - spilt_file('record.txt')   
 
  复制代码 
 
 
 |   
 
 
 
 |