2012-08-23 24 views
2
# -*- coding: utf-8 -*- 
from pyquery import PyQuery as pq 
from urllib import urlencode 
from urllib2 import Request,urlopen 
    def sendRequest(url, data = None, headersOnly = False): 
    headers = { 'User-Agent' : 'Mozilla/5.0 (X11; U; Linux i686; en-US;)' } 
    request = Request(url, data, headers) 
    return urlopen(request).read() 

resp = sendRequest("https://foursquare.com/v/rivers-edge-cafe-- morrison/4c1907776e02b7132eae627b") 
print pq(resp)("#venueCategories").text() 

輸出應該是咖啡館,漢堡店,三明治廣場 但有例外:Python 2.5的編碼

Traceback (most recent call last): 
    File "unicodeerr1.py", line 11, in <module> 
    print pq(resp)("#venueCategories").text() 
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 3: ordinal not in range(128) 
+0

這可能是您的終端本地化問題。 –

回答

7

你需要指定編碼源代碼,或者使用一個字符,而不是逃避。

# -*- coding: utf-8 -*- 

print 'caf\xc3\xa9' # UTF-8 representation of e accent egu. 

你可能想使用Unicode文本雖然(這裏以Unicode轉義字符):

print u'caf\u00e9' 

請務必閱讀Unicode HOWTO充分了解發生的事情在這。其他有用的文件:

請注意,您的特定錯誤不會有任何與蟒蛇2.5 2.7對,但一切都與任何您要打印的編碼輸出。在你的服務器上使用python2.5,沒有指定編碼,或者顯式設置爲ASCII,但是在本地機器上使用python 2.7,你最有可能處理支持UTF-8的終端。

0

我剛升級到python 2.7,我所有的編碼問題都修復了。