2010-06-30 149 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