2010-06-30 148 views
3

我收到非常熟悉:UnicodeEncodeError谷歌应用程序引擎

UnicodeEncodeError: 'ASCII' 编解码器不能编码字符U '\ xe8' 在位置24:在范围序数不(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"])) 

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

+0

包括你的代码和stacktrace肯定不会受到伤害。 :) – 2010-06-30 21:38:06

+0

尼克,已更新帖子。任何帮助将不胜感激。 我知道你是一个应用程序引擎大师,所以如果你可以,请帮助我,以及以下:http://stackoverflow.com/questions/3151237/math-comparison-operating-in-django-96-templates – demos 2010-07-01 03:03:12

回答

8

Python有两种不同的东西被视为字符串 - “原始”字符串和“unicode”字符串。只有后者实际上代表了文字。如果你有一个原始字符串,并且你想把它当作文本,你首先需要将它转换为一个unicode字符串。要做到这一点,你需要知道字符串的编码 - 他们的方式unicode代码点表示为原始字符串中的字节 - 并在原始字符串上调用.decode(编码)。

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

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

  • 代表“imageAltTags”为Unicode字符串列表,从而转储STR()调用 - 这可能是最好的办法
  • 相反str(x),调用x.encode(encoding)。要使用的编码取决于你在做什么,但最可能的选择是utf-8 - 例如x.encode('utf-8')。
+1

这是Python 2用户每天都遇到的常见问题。它发生了很多,我结束了博客有关它... http://wesc.livejournal.com/1743.html – wescpy 2010-07-03 08:44:20

+0

我甩了str(),现在事情工作正常。我将所有内容都作为unicode字符串处理。谢谢! – demos 2010-07-03 14:48:11