终于我明白了:
as3:/usr/local/lib/python2.7/site-packages# cat sitecustomize.py # encoding=utf8 import sys reload(sys) sys.setdefaultencoding('utf8')
我来看看:
as3:~/ngokevin-site# python Python 2.7.6 (default, Dec 6 2013, 14:49:02) [GCC 4.4.5] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import sys >>> reload(sys)>>> sys.getdefaultencoding() 'utf8' >>>
上面显示了python的默认编码是utf8
.然后错误就不复存在了.
这是经典的"unicode问题".我相信解释这一点超出了StackOverflow答案的范围,可以完全解释发生的事情.
这里有很好的解释.
在非常简短的总结中,您已经将一些被解释为字节串的东西传递给需要将其解码为Unicode字符的东西,但是默认的编解码器(ascii)失败了.
我指出的演示文稿提供了避免这种情况的建议.使您的代码成为"unicode三明治".在Python 2中,使用"from __future__ import unicode_literals"会有所帮助.
更新:如何修复代码:
好的 - 在变量"source"中你有一些字节.从你的问题不清楚他们是如何进入那里的 - 也许你是从网络表格中读到的?在任何情况下,它们都不是用ascii编码的,但python试图将它们转换为unicode,假设它们是.您需要明确告诉它编码是什么.这意味着您需要知道编码是什么!这并不总是容易的,它完全取决于这个字符串的来源.您可以尝试一些常见的编码 - 例如UTF-8.你告诉unicode()编码作为第二个参数:
source = unicode(source, 'utf-8')
在某些情况下,当您检查默认编码(print sys.getdefaultencoding()
)时,它会返回您使用的ASCII.如果更改为UTF-8,则它不起作用,具体取决于变量的内容.我找到了另一种方式:
import sys reload(sys) sys.setdefaultencoding('Cp1252')
终于我明白了:
as3:/usr/local/lib/python2.7/site-packages# cat sitecustomize.py # encoding=utf8 import sys reload(sys) sys.setdefaultencoding('utf8')
我来看看:
as3:~/ngokevin-site# python Python 2.7.6 (default, Dec 6 2013, 14:49:02) [GCC 4.4.5] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import sys >>> reload(sys) <module 'sys' (built-in)> >>> sys.getdefaultencoding() 'utf8' >>>
上面显示了python的默认编码是utf8
.然后错误就不复存在了.
Encode将unicode对象转换为字符串对象.我想你正在尝试编码一个字符串对象.首先将结果转换为unicode对象,然后将该unicode对象编码为'utf-8'.例如
result = yourFunction() result.decode().encode('utf-8')
"UnicodeDecodeError: 'ascii' codec can't decode byte"
导致此错误的原因:input_string必须是unicode但是给出了str
"TypeError: Decoding Unicode is not supported"
此错误的原因:尝试将unicode input_string转换为unicode
因此,首先检查您的input_string str
是否必要,并在必要时转换为unicode:
if isinstance(input_string, str): input_string = unicode(input_string, 'utf-8')
其次,上面只是更改类型但不删除非ascii字符.如果要删除非ascii字符:
if isinstance(input_string, str): input_string = input_string.decode('ascii', 'ignore').encode('ascii') #note: this removes the character and encodes back to string. elif isinstance(input_string, unicode): input_string = input_string.encode('ascii', 'ignore')
reload
)这是一个讨厌的黑客(你必须使用的原因UnicodeDecodeError: 'ascii' codec can't decode byte
)只会掩盖问题并阻碍你迁移到Python 3.x. 了解问题,修复根本原因并享受Unicode zen.请参阅为什么我们不应该在py脚本中使用sys.setdefaultencoding("utf-8")?了解更多详情
不要随便解码/编码
不要假设您的字符串是UTF-8编码的
尝试在代码中尽快将字符串转换为Unicode字符串
如果没有看到来源,就很难知道根本原因,所以我不得不一般地说.
str
当您尝试将unicode()
包含非ASCII 的Python 2.x转换为Unicode字符串而不指定原始字符串的编码时,通常会发生这种情况.
简而言之,Unicode字符串是完全独立的Python字符串类型,不包含任何编码.它们只保存Unicode 点代码,因此可以保存整个频谱中的任何Unicode点.字符串包含编码文本,beit UTF-8,UTF-16,ISO-8895-1,GBK,Big5等.字符串被解码为Unicode,而Unicodes被编码为字符串.文件和文本数据始终以编码字符串传输.
Markdown模块作者可能会使用u
(抛出异常的地方)作为代码其余部分的质量门 - 它将转换ASCII或将现有的Unicodes字符串重新包装为新的Unicode字符串.Markdown作者无法知道传入字符串的编码,因此在传递给Markdown之前,您将依赖于将字符串解码为Unicode字符串.
可以使用str
字符串前缀在代码中声明Unicode 字符串.例如
>>> my_u = u'my ünicôdé str?ng' >>> type(my_u) <type 'unicode'>
Unicode字符串也可能来自文件,数据库和网络模块.发生这种情况时,您无需担心编码.
unicode()
即使您没有显式调用,也可能会发生从Unicode 转换UnicodeDecodeError
.
以下方案会导致café
异常:
# Explicit conversion without encoding
unicode('€')
# New style format string into Unicode string
# Python will try to convert value string to Unicode first
u"The currency is: {}".format('€')
# Old style format string into Unicode string
# Python will try to convert value string to Unicode first
u'The currency is: %s' % '€'
# Append string to Unicode
# Python will try to convert string to Unicode first
u'The currency is: ' + '€'
在下图中,您可以看到单词caf
是如何编码的,以"UTF-8"或"Cp1252"编码,具体取决于终端类型.在这两个例子中,é
只是常规的ascii.在UTF-8中,decode()
使用两个字节进行编码.在"Cp1252"中,é是0xE9(这也恰好是Unicode点值(这不是巧合)).decode()
调用正确并成功转换为Python Unicode:
在此图中,ascii
调用with unicode()
(与0x7F
没有给出编码的调用相同).由于ASCII不能包含大于的字节UnicodeDecodeError
,因此会抛出str
异常:
在您的代码中形成Unicode三明治是一种很好的做法,您可以将所有传入数据解码为Unicode字符串,使用Unicodes,然后u
在出路时编码为s.这样可以避免担心代码中间的字符串编码.
如果需要在源代码中加入非ASCII,只需在字符串前加上a即可创建Unicode字符串io
.例如
u'Zürich'
要允许Python解码源代码,您需要添加一个编码头以匹配文件的实际编码.例如,如果您的文件编码为"UTF-8",您将使用:
# encoding: utf-8
只有在源代码中包含非ASCII时才需要这样做.
通常从文件接收非ASCII数据.该encoding
模块提供了一个TextWrapper,它使用给定的动态解码您的文件my_unicode_string
.您必须使用正确的文件编码 - 它不容易被猜到.例如,对于UTF-8文件:
import io with io.open("my_utf8_file.txt", "r", encoding="utf-8") as my_file: my_unicode_string = my_file.read()
UnicodeDecodeError
那么适合传递给Markdown.如果read()
来自该Content-type
行,那么您可能使用了错误的编码值.
Python 2.7 CSV模块不支持非ASCII字符.但是,使用https://pypi.python.org/pypi/backports.csv即可获得帮助.
像上面一样使用它,但将打开的文件传递给它:
from backports import csv import io with io.open("my_utf8_file.txt", "r", encoding="utf-8") as my_file: for row in csv.reader(my_file): yield row
大多数Python数据库驱动程序都可以以Unicode格式返回数据,但通常需要一些配置.始终使用Unicode字符串进行SQL查询.
MySQL的在连接字符串中添加:
charset='utf8', use_unicode=True
例如
>>> db = MySQLdb.connect(host="localhost", user='root', passwd='passwd', db='sandbox', use_unicode=True, charset="utf8")PostgreSQL的
加:
psycopg2.extensions.register_type(psycopg2.extensions.UNICODE) psycopg2.extensions.register_type(psycopg2.extensions.UNICODEARRAY)
网页可以使用任何编码进行编码.的charset
报头应包含一个response.text
字段在编码暗示.然后可以针对该值手动解码内容.或者,Python-Requests返回Unicodes my_string.decode(encoding)
.
如果你必须手动解码字符串,你可以简单地做encoding
,UnicodeDecodeError
适当的编码在哪里.Python 2.x支持的编解码器在这里给出:标准编码.再说一遍,如果你得到print
那么你可能得到了错误的编码.
像普通人一样使用Unicodes.
locale
通过stdout流写入.Python尝试在stdout上配置编码器,以便将Unicodes编码为控制台的编码.例如,如果Linux外壳的en_GB.UTF-8
是UTF-8
,输出将被编码以PYTHONIOENCODING
.在Windows上,您将被限制为8位代码页.
配置不正确的控制台(例如损坏的区域设置)可能会导致意外的打印错误.io.open
环境变量可以强制stdout的编码.
就像输入一样,str
可以用来透明地将Unicodes转换为编码的字节串.
读取的相同配置将允许直接写入Unicodes.
Python 3不再像Python 2.x那样具有Unicode功能,但是常规str
现在是一个Unicode字符串,bytes
现在是旧的.decode()
.
默认编码现在是UTF-8,因此如果您open()
没有给出编码的字节字符串,Python 3将使用UTF-8编码.这可能解决了50%的人的Unicode问题.
此外,str
默认情况下以文本模式运行,因此返回已解码的sys.setdefaultencoding('utf8')
(Unicode).编码源自您的语言环境,它在Un*x系统上为UTF-8,在Windows框上为8位代码页,如windows-1251.
我正在搜索以解决以下错误消息:
unicodedecodeerror:'ascii'编解码器无法解码5454位的字节0xe2:序号不在范围内(128)
我终于通过指定'encoding'来修复它:
f = open('../glove/glove.6B.100d.txt', encoding="utf-8")
希望它也可以帮到你.
我发现最好总是转换为unicode - 但这很难实现,因为在实践中你必须检查并将每个参数转换为你编写的每个函数和方法,包括某种形式的字符串处理.
所以我提出了以下方法来保证来自任一输入的unicodes或字符串.简而言之,包括并使用以下lambdas:
# guarantee unicode string _u = lambda t: t.decode('UTF-8', 'replace') if isinstance(t, str) else t _uu = lambda *tt: tuple(_u(t) for t in tt) # guarantee byte string in UTF8 encoding _u8 = lambda t: t.encode('UTF-8', 'replace') if isinstance(t, unicode) else t _uu8 = lambda *tt: tuple(_u8(t) for t in tt)
例子:
text='Some string with codes > 127, like Zürich' utext=u'Some string with codes > 127, like Zürich' print "==> with _u, _uu" print _u(text), type(_u(text)) print _u(utext), type(_u(utext)) print _uu(text, utext), type(_uu(text, utext)) print "==> with u8, uu8" print _u8(text), type(_u8(text)) print _u8(utext), type(_u8(utext)) print _uu8(text, utext), type(_uu8(text, utext)) # with % formatting, always use _u() and _uu() print "Some unknown input %s" % _u(text) print "Multiple inputs %s, %s" % _uu(text, text) # but with string.format be sure to always work with unicode strings print u"Also works with formats: {}".format(_u(text)) print u"Also works with formats: {},{}".format(*_uu(text, text)) # ... or use _u8 and _uu8, because string.format expects byte strings print "Also works with formats: {}".format(_u8(text)) print "Also works with formats: {},{}".format(*_uu8(text, text))
以下是对此的更多推理.
为了在Ubuntu安装中的操作系统级别解决此问题,请检查以下内容:
$ locale charmap
如果你得到
locale: Cannot set LC_CTYPE to default locale: No such file or directory
代替
UTF-8
然后设置LC_CTYPE
,LC_ALL
像这样:
locale: Cannot set LC_CTYPE to default locale: No such file or directory