【问题标题】:Unicode issue, correctly decoding/encoding string in pythonUnicode问题,在python中正确解码/编码字符串
【发布时间】:2011-07-14 05:47:57
【问题描述】:

我正在使用 BeautifulSoup,我得到一个这样的字符串:

u'Dassault Myst\xe8re'

这是一个 unicode,但我想要让它看起来像:

'Dassault Mystère'

我试过了

name = name.encode('utf-8'), decode(), unicode()

我不断收到的错误是:

UnicodeEncodeError: 'ascii' codec can't encode character u'\xe8'

我的默认编码似乎是“ascii”:sys.getdefaultencoding() 即使我有,也会返回“ascii”:

#!/usr/bin/env python
# encoding: utf-8

在文件的顶部。

希望一劳永逸地解决这个反复出现的 Unicode 问题!

谢谢

【问题讨论】:

    标签: python unicode utf-8 ascii


    【解决方案1】:

    我不知道你是如何以及从哪里得到这个消息的,但是看看这个例子:

    $ python
    Python 2.6.1 (r261:67515, Jun 24 2010, 21:47:49) 
    [GCC 4.2.1 (Apple Inc. build 5646)] on darwin
    Type "help", "copyright", "credits" or "license" for more information.
    >>> txt = u'Dassault Myst\xe8re'
    >>> txt
    u'Dassault Myst\xe8re'
    >>> print txt
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      UnicodeEncodeError: 'ascii' codec can't encode character u'\xe8' in position 13:
      ordinal not in range(128)
    >>> ^D
    $ export LANG=en_US.UTF-8
    $ python
    Python 2.6.1 (r261:67515, Jun 24 2010, 21:47:49) 
    [GCC 4.2.1 (Apple Inc. build 5646)] on darwin
    Type "help", "copyright", "credits" or "license" for more information.
    >>> txt = u'Dassault Myst\xe8re'
    >>> txt
    u'Dassault Myst\xe8re'
    >>> print txt
    Dassault Mystère
    >>>^D 
    

    所以你可以看到你是否有一个 ASCII 控制台,然后在打印过程中,有一个从 unicode 到 ascii 的转换,如果有 ASCII 范围之外的字符 - 就会抛出异常。

    但如果控制台可以接受 unicode,那么一切都会正确显示。

    【讨论】:

    • 嗯,这解决了打印到控制台的问题。但是在构建 url 时我仍然遇到问题,因为当我将 - u'Dassault Myst\xe8re' 附加到 url 时,urllib2 在发出 http 请求时会阻塞它。我猜它期待一个 ascii 字符串,而我正在发送其他内容?
    • 我的 url 看起来像这样:u'youtube.com/results?search_query=Dassault+Myst\xe8re&aq=0' 而 urllib2 看起来不喜欢这样。
    • 第二部分使用这个答案解决:stackoverflow.com/questions/4389572/…
    • 我相信 urllib2 可以与 "from future import unicode_literals" 一起正常工作。
    猜你喜欢
    • 1970-01-01
    • 2017-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-09
    • 1970-01-01
    • 2016-04-01
    • 1970-01-01
    相关资源
    最近更新 更多