首页 > 解决方案 > 你能用 tweepy 只询问 10 个趋势吗?

问题描述

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

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

标签: pythontwittertweepy

解决方案


API.trends_place方法/ GET 趋势/地点端点返回的趋势列表不一定按最流行的顺序排列,因此如果您想获得前 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 问题的答案和评论所指出的那样,在您的代码段中泄漏文件对象是一种不好的做法。请参阅有关读取和写入文件的 Python 教程

另一方面,如果您只是想要前 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)

推荐阅读