UnicodeEncodeError Google App Engine

dem*_*mos 3 unicode google-app-engine

我变得非常熟悉了:

UnicodeEncodeError:'ascii'编解码器无法对位置24中的字符u'\ xe8'进行编码:序数不在范围内(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)
Run Code Online (Sandbox Code Playgroud)

负责相同的代码:

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"]))
Run Code Online (Sandbox Code Playgroud)

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

Nic*_*son 8

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

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

相反,你应该做两件事之一:

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