【问题标题】:Can you ask for only 10 trends using tweepy?你能用 tweepy 只询问 10 个趋势吗?
【发布时间】:2019-11-18 10:12:58
【问题描述】:

所以,我正在重写这个,但我使用 Tweepy 来获取趋势,我只想要 10 个,而不是标准的 50 个趋势。我曾尝试使用网站上的其他代码(hereherehere.)并实现它,但无济于事。这是一段 sn-p 代码。

import time
import tweepy
auth = tweepy.OAuthHandler(APIKey, APIKeysecret)
auth.set_access_token(AccessToken, AccessTokenSecret)
api = tweepy.API(auth)
trends1 = api.trends_place(1, '#')
data = trends1[0] 
trends = data['trends']
names = [trend['name'] for trend in trends]
trendsName = '\n'.join(names)
print(trendsName, file=open("trends.txt", "w"))

【问题讨论】:

  • 对不起!我已经更新了帖子以反映规则。

标签: python twitter tweepy


【解决方案1】:

API.trends_place method/GET trends/place endpoint返回的趋势列表不一定按最流行的顺序排列,所以如果你想获得前10个趋势,你必须按"tweet_volume"排序,例如:

from operator import itemgetter

import tweepy

auth = tweepy.OAuthHandler(CONSUMER_API_KEY, CONSUMER_API_SECRET_KEY)
auth.set_access_token(ACCESS_TOKEN, ACCESS_TOKEN_SECRET)
api = tweepy.API(auth)
data = api.trends_place(1, '#')
trends = data[0]["trends"]
# Remove trends with no Tweet volume data
trends = filter(itemgetter("tweet_volume"), trends)
# Alternatively, using 0 during sorting would work as well:
# sorted(trends, key=lambda trend: trend["tweet_volume"] or 0, reverse=True)
sorted_trends = sorted(trends, key=itemgetter("tweet_volume"), reverse=True)
top_10_trend_names = '\n'.join(trend['name'] for trend in sorted_trends[:10])
with open("trends.txt", 'w') as trends_file:
    print(top_10_trend_names, file=trends_file)

请注意,正如您链接的 Stack Overflow 问题的答案和 cmets 所指出的那样,像在您的 sn-p 中泄漏文件对象是不好的做法。见The Python Tutorial on Reading and Writing Files

另一方面,如果您只是想要前 50 个趋势中的任何 10 个,您可以简单地索引您已有的趋势列表,例如:

import tweepy

auth = tweepy.OAuthHandler(CONSUMER_API_KEY, CONSUMER_API_SECRET_KEY)
auth.set_access_token(ACCESS_TOKEN, ACCESS_TOKEN_SECRET)
api = tweepy.API(auth)
data = api.trends_place(1, '#')
trends = data[0]["trends"]
ten_trend_names = '\n'.join(trend['name'] for trend in trends[:10])
with open("trends.txt", 'w') as trends_file:
    print(ten_trend_names, file=trends_file)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-03-08
    • 1970-01-01
    • 2018-03-10
    • 2014-02-07
    • 2019-07-06
    • 1970-01-01
    • 1970-01-01
    • 2011-09-19
    相关资源
    最近更新 更多