Unicode编码错误:'ascii' 编解码器无法编码位置0-3的字符:序数不在范围内(128)
当我运行我的代码时,出现了这个错误:
UserId = "{}".format(source[1]) UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-3: ordinal not in range(128)
我的代码是:
def view_menu(type, source, parameters):
ADMINFILE = 'static/users.txt'
fp = open(ADMINFILE, 'r')
users = ast.literal_eval(fp.read())
if not parameters:
if not source[1] in users:
UserId = "{}".format(source[1])
users.append(UserId)
write_file(ADMINFILE,str(users))
fp.close()
reply(type, source, u"test")
else:
reply(type, source, u"test")
register_command_handler(view_menu, 'test', ['info','muc','all'], 0, '')
请问我该如何解决这个问题。
谢谢你
4 个回答
-2
你的文件 static/users.txt
必须包含一些非Unicode字符。你需要在你的程序中指定编码方式,比如 utf-8
。想了解更多内容,可以查看这里: Unicode 使用指南。
0
一个解决办法是在你的 sitecustomize.py 文件中把默认编码设置为 utf-8,而不是 ascii。
5
在处理未知编码的字符串时,可以使用这些函数:
你想要处理文本吗?
def read_unicode(text, charset='utf-8'):
if isinstance(text, basestring):
if not isinstance(text, unicode):
text = unicode(obj, charset)
return text
如果你想把文本存储起来,比如放在数据库里,可以使用这个:
def write_unicode(text, charset='utf-8'):
return text.encode(charset)
6
问题在于 "{}"
是一种非Unicode的 str
,而你试图把一个Unicode字符串放进去。Python 2.x 处理这个问题的方式是自动用 sys.getdefaultencoding()
来编码这个Unicode字符串,通常这个编码是 'ascii'
,但你的字符串里有一些非ASCII字符。
解决这个问题有两种方法:
明确地把那个
unicode
字符串编码成合适的字符集。比如,如果是UTF-8格式,可以这样做:"{}".format(source[1].encode('utf-8'))
。使用一个
unicode
格式的字符串:u"{}".format(source[1])
。你可能还需要在后面对这个UserId
进行编码;我不知道你的write_file
函数是怎么工作的。但一般来说,尽量保持所有内容都是Unicode,只有在最后才进行编码和解码,这样比混合使用两者要好。
说到这里,这行代码其实没什么用。"{}".format(foo)
会把 foo
转换成一个 str
,然后再格式化成完全一样的 str
。为什么呢?