【问题标题】:Can't decode utf-8 string in python on os x terminal.app无法在 os x terminal.app 上的 python 中解码 utf-8 字符串
【发布时间】:2010-10-21 23:28:15
【问题描述】:

我将 terminal.app 设置为接受 utf-8 并且在 bash 中我可以输入 unicode 字符,复制并粘贴它们,但是如果我启动 python shell 我不能,如果我尝试解码 unicode 我会得到错误:

>>> wtf = u'\xe4\xf6\xfc'.decode()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-2: ordinal not in range(128)
>>> wtf = u'\xe4\xf6\xfc'.decode('utf-8')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/encodings/utf_8.py", line 16, in decode
    return codecs.utf_8_decode(input, errors, True)
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-2: ordinal not in range(128)

有人知道我做错了什么吗?

【问题讨论】:

  • This 回答有关编码/解码的相关问题可能会有所帮助。

标签: python macos unicode terminal


【解决方案1】:

我认为你有向后编码和解码。您将 Unicode 编码为字节流,然后将字节流解码为 Unicode。

Python 2.6.1 (r261:67515, Dec  6 2008, 16:42:21) 
[GCC 4.0.1 (Apple Computer, Inc. build 5370)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> wtf = u'\xe4\xf6\xfc'
>>> wtf
u'\xe4\xf6\xfc'
>>> print wtf
äöü
>>> wtf.encode('UTF-8')
'\xc3\xa4\xc3\xb6\xc3\xbc'
>>> print '\xc3\xa4\xc3\xb6\xc3\xbc'.decode('utf-8')
äöü

【讨论】:

  • 嗯。 UTF-8 是一个已经编码的字节流,所以,虽然没有倒退,但至少你得到了它:) 也许你的意思是 Unicode 而不是 UTF-8。我会编辑你的帖子,让你决定。
【解决方案2】:

入门教程的Unicode strings 部分解释得很好:

为了使用特定编码将 Unicode 字符串转换为 8 位字符串,Unicode 对象提供了一个 encode() 方法,该方法接受一个参数,即编码的名称。编码的小写名称是首选。

>>> u"äöü".encode('utf-8')
'\xc3\xa4\xc3\xb6\xc3\xbc'

【讨论】:

  • 你不是在最后一行解码字符吗?
  • 是的,我已经消除了我的疲劳错误,unicode strings 部分比我能解释得更好..
【解决方案3】:
>>> wtf = '\xe4\xf6\xfc'
>>> wtf
'\xe4\xf6\xfc'
>>> print wtf
���
>>> print wtf.decode("latin-1")
äöü
>>> wtf_unicode = unicode(wtf.decode("latin-1"))
>>> wtf_unicode
u'\xe4\xf6\xfc'
>>> print wtf_unicode
äöü

【讨论】:

    【解决方案4】:

    我认为到处都存在编码/解码混乱。你从一个 unicode 对象开始:

    u'\xe4\xf6\xfc'
    

    这是一个 unicode 对象,三个字符是“äöü”的 unicode 代码点。如果你想把它们变成 Utf-8,你必须对它们进行encode

    >>> u'\xe4\xf6\xfc'.encode('utf-8')
    '\xc3\xa4\xc3\xb6\xc3\xbc'
    

    生成的六个字符是“äöü”的 Utf-8 表示。

    如果您调用decode(...),您会尝试将字符解释为仍需要转换为 unicode 的某种编码。因为它已经是 Unicode,所以这不起作用。您的第一次调用尝试将 Ascii 转换为 Unicode,第二次调用尝试将 Utf-8 转换为 Unicode。由于u'\xe4\xf6\xfc' 既不是有效的 Ascii 也不是有效的 Utf-8,因此这些转换尝试失败。

    '\xe4\xf6\xfc' 也是“äöü”的 Latin1/ISO-8859-1 编码可能会导致进一步的混淆。如果你编写一个普通的 python 字符串(没有将它标记为 unicode 的前导“u”),你可以使用 decode('latin1') 将其转换为 unicode 对象:

    >>> '\xe4\xf6\xfc'.decode('latin1')
    u'\xe4\xf6\xfc'
    

    【讨论】:

    • 啊哈。这终于有道理了。
    猜你喜欢
    • 2020-04-07
    • 2012-10-18
    • 1970-01-01
    • 1970-01-01
    • 2022-11-12
    • 1970-01-01
    • 1970-01-01
    • 2018-06-29
    • 2015-05-09
    相关资源
    最近更新 更多