你能用 tweepy 只要求 10 个趋势吗?

Can you ask for only 10 trends using tweepy?

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

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"))

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 问题的答案和评论所指出的那样,像您的代码片段中那样泄露文件对象是不好的做法。参见 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)