python - 搜索中文文本会抛出 UnicodeEncodeError

标签 python unicode python-2.7 python-twitter

我正在使用python-twiter使用 Twitter 的 API 搜索推文,但我遇到中文术语问题。这是重现该问题的最小代码示例:

# -*- 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)

最佳答案

GetSearch 中似乎存在错误:https://code.google.com/p/python-twitter/issues/detail?id=210 。我尝试用俄语(“Путин”)搜索“普京”,也得到了同样的错误。使用编码并没有帮助。

作为解决方法,您可以使用 twitter 包 ( https://github.com/sixohsix/twitter ):

# -*- coding: utf-8 -*-
from twitter import *

t = Twitter(auth=OAuth(token="...", token_secret="...", consumer_key="...", consumer_secret="...")))

print t.search.tweets(q=u"您说英语吗")

关于python - 搜索中文文本会抛出 UnicodeEncodeError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16268602/

相关文章:

python - Z3PY 方程,大小限制

python - 使用 git 项目的“正确”方式

unicode - Lua支持Unicode吗?

python - PyAudio - 将stream.read转换为int以获得幅度

python - 在 Python Pillow 上使用 JP2 图像

python - 将字符串列表转换为 float

python 带有可选参数的假设检验

Python 相当于 'grep -C N' ?

c++ - 对 unicode 文件使用 getline 时出现问题

python - 使用Selenium进行Web爬网-找不到元素