2011-10-03 83 views
65

我有我的Python中的編碼問題。我嘗試過不同的方法,但我似乎無法找到將我的輸出編碼爲UTF-8的最佳方式。解碼的Python不支持Unicode

這就是我要做的:

result = unicode(google.searchGoogle(param), "utf-8").encode("utf-8") 

searchGoogle返回第一個谷歌結果爲param

這是錯誤我得到:

exceptions.TypeError: decoding Unicode is not supported 

有誰知道我怎樣才能使Python編碼我輸出UTF-8來避免這個錯誤?

回答

83

貌似google.searchGoogle(param)已經返回unicode

>>> unicode(u'foo', 'utf-8') 

Traceback (most recent call last): 
    File "<pyshell#1>", line 1, in <module> 
    unicode(u'foo', 'utf-8') 
TypeError: decoding Unicode is not supported 

所以,你想要的是:

result = google.searchGoogle(param).encode("utf-8") 

作爲一個側面說明,你的代碼期望它返回一個utf-8編碼字符串,所以究竟是什麼點解碼(使用unicode())和編碼回(使用.encode())使用相同的編碼?

+4

老實說,在'的unicode()'只是打打鬧鬧試圖瞭解發生了什麼事。非常感謝你:-) – simonbs

+2

現在我有時會得到'ascii'編解碼器無法解碼位置字節0xc3。你知道這是爲什麼嗎? – simonbs

+2

在我建議的路線中?那麼這意味着searchGoogle()返回一個字符串爲0xC3的字符串。調用'.encode()'會導致Python試圖首先轉換爲unicode(使用ascii編碼)。我不知道爲什麼searchGoogle()有時會返回unicode,有時會返回一個字符串。也許這取決於你在'param'中給出了什麼?嘗試堅持一種類型。 – yak