繁体   English   中英

Unicode问题,在python中正确解码/编码字符串

[英]Unicode issue, correctly decoding/encoding string in python

我正在使用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
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,那么一切都会正确显示。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM