【问题标题】:Twython load 3200 tweets and encode it (Cyrillic text)Twython 加载 3200 条推文并对其进行编码(西里尔文)
【发布时间】:2014-12-21 12:01:13
【问题描述】:

我在 Python 3.4.2 上使用 Twython 模块 (3.1.2) 编写了小程序。 它有效,但并不完全正确。 程序加载推文并显示它们(您可以在下面查看代码)。它加载了 200 条推文,但我读到 Twitter API 可以访问 3200 条推文。我可以用 Twython 做到这一点吗? 主要问题 - 推文以不可读的形式加载 :( 我注意到这是因为推文是用西里尔文写的。

import sys
from twython import Twython

APP_KEY = 'MY_APP_KEY'
APP_SECRET = 'MY_APP_SECRET'
OAUTH_TOKEN = 'MY_OAUTH_TOKEN'
OAUTH_TOKEN_SECRET = 'MY_OAUTH_TOKEN_SECRET'

client_args = {
  "headers": {
    "accept-charset": "utf-8"
  }
}

twitter = Twython(APP_KEY, APP_SECRET,
                  OAUTH_TOKEN, OAUTH_TOKEN_SECRET)

user_tweets = twitter.get_user_timeline(screen_name='poroshenko',
                                        count=200)

for tweets in user_tweets:
   print (tweets['text'].encode('utf-8'))

【问题讨论】:

    标签: python-3.x twitter utf-8 encode twython


    【解决方案1】:

    将 count= 更改为 3200

    要打印推文,请参阅https://twython.readthedocs.org/en/latest/usage/special_functions.html

    用途:

    for tweet in user_tweets:
        tweet['text'] = Twython.html_for_tweet(tweet)
        print(tweet['text'])
    

    【讨论】:

    • 这没有帮助。如果将 count= 更改为 3200,仍然只能得到 200 个值。在 Twitter API 文档中说需要提供多个请求,但是在 Twython 中它是如何实现的呢?
    • 关于 .html_for_tweet(tweet) - 这只是用于打印的 html 格式。如果我不使用 encode('utf-8'),我会收到错误消息。 Traceback (most recent call last): File "C:\Python\Python3\projects\twitter.py", line 25, in <module> print (tweets['text']) File "C:\Python\Python3\lib\encodings\cp1251.py", line 19, in encode return codecs.charmap_encode(input,self.errors,encoding_table)[0] UnicodeEncodeError: 'charmap' codec can't encode character '\U0001f631' in position 89: character maps to <undefined>
    • 编码错误可能与您的终端有关。如果你在 Windows 上运行 chcp 65001
    【解决方案2】:

    你必须使用 max_id 参数。

    获得前 200 条推文后,您将获得最后一条推文(最旧的推文)的 id,然后再次调用 twitter API。假设这条推文 ID 是 lastId

    user_tweets = twitter.get_user_timeline(screen_name='poroshenko',count=200,max_id=str(long(lastId)-1))
    

    确保您在超出速率限制时也小心处理。

    【讨论】:

      猜你喜欢
      • 2011-12-21
      • 1970-01-01
      • 2013-10-29
      • 1970-01-01
      • 2012-04-06
      • 1970-01-01
      • 1970-01-01
      • 2015-07-28
      • 1970-01-01
      相关资源
      最近更新 更多