【问题标题】:UnicodeEncodeError Google App EngineUnicodeEncodeError Google App Engine
【发布时间】:2010-06-30 16:42:26
【问题描述】:

我越来越熟悉了:

UnicodeEncodeError: 'ascii' codec can't encode character u'\xe8' in position 24: ordinal not in range(128)

我查看了关于 SO 的多个帖子,他们推荐 - variable.encode('ascii', 'ignore')

但是,这不起作用。即使在此之后我也遇到了同样的错误......

堆栈跟踪:

'ascii' codec can't encode character u'\x92' in position 18: ordinal not in range(128)
Traceback (most recent call last):
  File "/base/python_runtime/python_lib/versions/1/google/appengine/ext/webapp/__init__.py", line 513, in __call__
    handler.post(*groups)
  File "/base/data/home/apps/autominer1/1.343038273644030157/siteinfo.py", line 2160, in post
    imageAltTags.append(str(image["alt"]))
UnicodeEncodeError: 'ascii' codec can't encode character u'\x92' in position 18: ordinal not in range(128)

负责相同的代码:

siteUrl = urlfetch.fetch("http://www."+domainName, headers = { 'User-Agent' : 'Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9b5) Gecko/2008032620 Firefox/3.0b5' } )


 webPage = siteUrl.content.decode('utf-8', 'replace').encode('ascii', 'replace')


 htmlDom = BeautifulSoup(webPage)

 imageTags = htmlDom.findAll('img', { 'alt' : True } )


 for image in imageTags :
                        if len(image["alt"]) > 3 :
                                imageAltTags.append(str(image["alt"]))

任何帮助将不胜感激。谢谢。

【问题讨论】:

  • 包含您的代码和堆栈跟踪肯定不会有什么坏处。 :)
  • 尼克,更新了帖子。任何帮助将不胜感激。我知道你是应用引擎大师,所以如果可以的话,也请帮助我:stackoverflow.com/questions/3151237/…

标签: google-app-engine unicode


【解决方案1】:

Python 将两种不同的东西视为字符串——“原始”字符串和“unicode”字符串。只有后者实际代表文本。如果您有一个原始字符串,并且想将其视为文本,则首先需要将其转换为 unicode 字符串。为此,您需要知道字符串的编码——它们以原始字符串中的字节表示 unicode 代码点的方式——并在原始字符串上调用 .decode(encoding)。

当您在 unicode 字符串上调用 str() 时,会发生相反的转换 - Python 将 unicode 字符串编码为字节。如果不指定字符集,则默认为 ascii,只能表示前 128 个码点。

相反,您应该做以下两件事之一:

  • 将“imageAltTags”表示为 unicode 字符串列表,从而转储 str() 调用 - 这可能是最好的方法
  • 调用 x.encode(encoding) 代替 str(x)。要使用的编码取决于您在做什么,但最可能的选择是 utf-8 - 例如 x.encode('utf-8')。

【讨论】:

  • 这是 Python 2 用户每天都会遇到的常见问题。它发生得太多了,以至于我最终写了一篇关于它的博客……wesc.livejournal.com/1743.html
  • 我抛弃了 str(),现在一切正常。我将所有内容都作为 unicode 字符串处理。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-02-14
  • 2011-02-11
  • 2011-10-25
  • 2011-10-10
  • 1970-01-01
  • 2018-04-28
  • 1970-01-01
相关资源
最近更新 更多