| 
 | 
 
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册  
 
x
 
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(r'E:\学习\python学习\communicate.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(r'E:\学习\python学习\communicate.txt') 
 
 
 
Traceback (most recent call last): 
  File "E:/学习/python学习/6day.py", line 41, in <module> 
    split_file(r'E:\学习\python学习\communicate.txt') 
  File "E:/学习/python学习/6day.py", line 23, in split_file 
    for each_line in f: 
UnicodeDecodeError: 'gbk' codec can't decode byte 0xae in position 30: illegal multibyte sequence 
 
这是什么错误呢?我检查不出来哪里出错了。 
 
 本帖最后由 昨非 于 2020-10-9 22:25 编辑 
见第十八行
 - #定义写入函数
 
 - 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
 
 -             
 
 -         save_file(boy,girl,count)  #第三段内容(上方for循环漏掉一次写入)
 
 -         f.close()    
 
 -         
 
 -     
 
 -     
 
 - spilt_file('record.txt')   
 
 -     
 
  复制代码 
 
 
 |   
 
 
 
 |