【问题标题】:UnicodeEncodeError: 'ascii' codec can't encode character u'\xe7' in position 17710: ordinal not in range(128)UnicodeEncodeError:'ascii' 编解码器无法在位置 17710 编码字符 u'\xe7':序数不在范围内(128)
【发布时间】:2012-05-06 12:53:31
【问题描述】:

我正在尝试从archived web crawl 打印一个字符串,但是当我这样做时出现此错误:

print page['html']
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe7' in position 17710: ordinal not in range(128)

当我尝试打印 unicode(page['html']) 时,我得到:

print unicode(page['html'],errors='ignore')
TypeError: decoding Unicode is not supported

知道如何正确编码这个字符串,或者至少让它打印出来吗?谢谢。

【问题讨论】:

标签: python unicode character-encoding web-scraping


【解决方案1】:

你需要encode你保存的unicode来显示它,而不是decode它——unicode是未编码的形式。您应该始终指定编码,以便您的代码可移植。 “通常”的选择是utf-8

print page['html'].encode('utf-8')

如果您不指定编码,它是否有效将取决于您 printing 的对象——您的编辑器、操作系统、终端程序等。

【讨论】:

    猜你喜欢
    • 2016-08-26
    • 2017-03-29
    • 2011-07-05
    • 2018-07-10
    • 2012-04-14
    • 2016-09-05
    • 2013-02-11
    • 2019-12-15
    • 2014-08-07
    相关资源
    最近更新 更多