簡體   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