2011-01-24 43 views
0

我需要執行Google搜索才能檢索查詢的結果數量。我在這裏找到答案 - Google Search from a Python App嘗試撥打Google搜索API的Unicode錯誤

但是,對於少數查詢,我得到了以下錯誤。我認爲查詢有unicode字符。

UnicodeDecodeError錯誤:「ASCII」編解碼器不能在位置28進行解碼字節0xc3:在範圍內(128)

我搜索谷歌,發現我需要的unicode轉換爲ASCII序數不,和下面的代碼中發現。

def convertToAscii(text, action): 
      temp = unicode(text, "utf-8") 
      fixed = unicodedata.normalize('NFKD', temp).encode('ASCII', action) 
      return fixed 
    except Exception, errorInfo: 
      print errorInfo 
      print "Unable to convert the Unicode characters to xml character entities" 
      raise errorInfo 

如果我使用操作忽略,它將刪除這些字符,但如果我使用其他操作,則會收到異常。

任何想法,如何處理?

感謝

== ==編輯 我使用下面的代碼進行編碼,然後進行搜索,這是引發錯誤。

查詢= urllib.urlencode({ 'Q':searchfor})

+0

你使用的是什麼版本的Python? – Turtle 2011-01-24 01:41:25

+0

我正在使用python 2.6.4 – Boolean 2011-01-24 01:44:44

回答

2

您不能urlencode原始Unicode字符串。您需要先將它們編碼成UTF-8,然後喂到它:

query = urllib.urlencode({'q': u"München".encode('UTF-8')})

這將返回q=M%C3%BCnchen其中谷歌愉快地接受了。

0

你不能安全地轉換Unicode爲ASCII。這樣做涉及丟棄信息(具體地說,它會丟棄非英文字母)。

您應該在Unicode中完成整個過程,以免丟失任何信息。