鱼C论坛

 找回密码
 立即注册
查看: 2313|回复: 1

第29讲,按照下小甲鱼老师的讲解,敲了一下代码,但是报错,该解决

[复制链接]
发表于 2017-5-20 18:47:07 | 显示全部楼层 |阅读模式
5鱼币
f = open('/Users/xiaobingbing/Desktop/record.txt',encoding='utf-8')

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',encoding='utf-8')
        girl_file = open(file_name_girl,'w',encoding='utf-8')

        boy_file.writelines(boy)
        girl_file.writelines(girl)

        boy_file.close()
        girl_file.close()

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

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

f.close()
报错内容是:
Traceback (most recent call last):
  File "/Users/xiaobingbing/Desktop/Python/第29讲-分割文本文件.py", line 40, in <module>
    boy_file.writelines(boy)
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-5: ordinal not in range(128)
请问各位大牛,我是得把系统默认代码改掉么?该怎么改?还是有其他的办法,涉及到文件编码问题我的mac总是出现这个问题
我用的是Mac os 10.12      Python版本是3.6.1

想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

 楼主| 发表于 2017-5-20 23:17:28 | 显示全部楼层
底下的boy_file和girl_file的编码方式也改成encoding='utf-8'形式
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-10-8 04:31

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表