The list of trends returned by the API.trends_place
method / GET trends/place endpoint is not necessarily in order of most trending, so if you want to get the top 10 trends, you'll have to sort by "tweet_volume"
, e.g.:
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)
Note, as the answers and comments for the Stack Overflow questions you linked point out, it's bad practice to leak a file object like in your snippet. See The Python Tutorial on Reading and Writing Files.
On the other hand, if you simply want any 10 of the top 50 trends, you can simply index the trends list you already have, e.g.:
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)