【问题标题】:grab tweet with python encounters UnicodeEncodeError用python抓取推文遇到UnicodeEncodeError
【发布时间】:2013-10-09 11:50:10
【问题描述】:

我正在尝试使用 Twittter API 和 Python 获取推文文本

我使用 oauth 登录并获取结果字典:

jsonTweets = json.loads(response)
list = jsonTweets["statuses"]   # list of dictionaries

type(jsonTweets)  #returns dict
type(list)    #returns list
type(list[0])    #return dict (it's a list of dictionaries)

list[0] 是一个字典:

{u'contributors': None, u'truncated': False, u'text': u'RT @Kagame_quotes: "We, the people of #Rwanda, our country has its own problems that we can\u2019t attribute to others, we need to find solution\u2026', u'in_reply_to_status_id': None, u'id': 387905246028394496L, u'favorite_count': 0, u'source': u'<a href="http://twitter.com" rel="nofollow">Twitter Web Client</a>', u'retweeted': False, u'coordinates': None, 等等...

我只想获取u'text' 键的值(即获取推文)

所以我写:

for item in list:
    print item[u'text']

但这给了我错误:

UnicodeEncodeError: 'ascii' codec can't encode character u'\u2019'
in position 91: ordinal not in range(128)

如何获取u'text' 键的值?

【问题讨论】:

  • 不要使用list作为变量名。

标签: python json twitter unicode


【解决方案1】:

您需要指定 UTF-8 编码:

for item in list:
    print item[u'text'].encode('utf-8')

这应该可以解决问题。

【讨论】:

    【解决方案2】:

    您的文字没有问题。它只包含 unicode 字符,您无法在控制台上打印。

    特别是(查看http://www.utf8-chartable.de/unicode-utf8-table.pl):

    • U+2019 右单引号
    • U+2026 水平省略号

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-27
      • 2015-06-18
      • 2019-01-31
      • 2022-12-04
      相关资源
      最近更新 更多