0

So, I am rewriting this, but I am using Tweepy to get trends, and I want only 10, not the standard, 50 trends. I have tried using other code from websites, (here, here and here.) and implementing it, but to no avail. Here is a snippet of code.

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"))
TwitApp
  • 15
  • 4

1 Answers1

1

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)
Harmon758
  • 5,084
  • 3
  • 22
  • 39