我收到了产品信息的xml Feed.信息为英文,但未编码utf-8(智能引号,版权符号等).要处理信息,我需要将其转换为utf-8.
我尝试过以下变体:
u'%s' % data
codecs.open(..., 'utf-8')
unicode(data)
Run Code Online (Sandbox Code Playgroud)
但对于每一个我尝试过的人,我都得到了UnicodeDecodeError(各种各样的).
我如何将所有这些文本转换成utf-8?
更新
感谢您的帮助,以下是最终的工作:
encoded_data = data.decode('ISO 8859-1').encode('utf-8').replace('Â','')
Run Code Online (Sandbox Code Playgroud)
我不知道它Â来自哪里,但我看到了一些版权符号旁边的那些.
Ada*_*eld 15
为了将其转换为UTF-8,您需要知道它的编码.根据您的描述,我猜它是在Latin-1变体之一,ISO 8859-1或Windows-1252.如果是这种情况,那么您可以将其转换为UTF-8,如下所示:
data = 'Copyright \xA9 2012' # \xA9 is the copyright symbol in Windows-1252
# Convert from Windows-1252 to UTF-8
encoded = data.decode('Windows-1252').encode('utf-8')
# Prints "Copyright © 2012"
print encoded
Run Code Online (Sandbox Code Playgroud)
您可以让chardet代表您猜测编码,而不是猜测编码:
import chardet
def read(filename, encoding=None, min_confidence=0.5):
"""Return the contents of 'filename' as unicode, or some encoding."""
with open(filename, "rb") as f:
text = f.read()
guess = chardet.detect(text)
if guess["confidence"] < min_confidence:
raise UnicodeDecodeError
text = unicode(text, guess["encoding"])
if encoding is not None:
text = text.encode(encoding)
return text
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5675 次 |
| 最近记录: |