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)