我正在使用python-twiter來搜索使用Twitter API的推文,並且我遇到了中文問題。下面是一個最小的代碼示例來重現問題:正在搜索中文文本拋出UnicodeEncodeError
# -*- coding: utf-8 -*-
import twitter
api = twitter.Api(consumer_key = "...", consumer_secret = "...",
access_token_key = "...", access_token_secret = "...")
api.VerifyCredentials()
print u"您說英語嗎"
r = api.GetSearch(term=u"您說英語嗎")
我得到這個錯誤:
您說英語嗎
Traceback (most recent call last):
File "so.py", line 9, in <module>
r = api.GetSearch(term=u"您說英語嗎")
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/python_twitter-0.8.7-py2.7.egg/twitter.py", line 2419, in GetSearch
json = self._FetchUrl(url, parameters=parameters)
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/python_twitter-0.8.7-py2.7.egg/twitter.py", line 4041, in _FetchUrl
url = req.to_url()
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/oauth2-1.5.211-py2.7.egg/oauth2/__init__.py", line 440, in to_url
urllib.urlencode(query, True), fragment)
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib.py", line 1337, in urlencode
l.append(k + '=' + quote_plus(str(elt)))
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-4: ordinal not in range(128)
之前添加以下代碼,你試過編碼呢? 'u「您說英語嗎」.encode('utf8')' – juliomalegria 2013-04-28 22:51:43