#import time
import tweepy
#import csv
import keys
#WOEID 455825
auth = tweepy.OAuthHandler("", "")
auth.set_access_token("",
"")
auth = tweepy.OAuthHandler(keys.consumer_key,
keys.consumer_secret)
auth.set_access_token(keys.access_token,
keys.access_token_secret)
api = tweepy.API(auth, wait_on_rate_limit = True,
wait_on_rate_limit_notify = True)
trends_available = api.trends_available()
print(f"Number of Trends availables: {len(trends_available)}")
print()
rj_trends = api.trends_place(id =23424768 )
#23424768 Brasil
#print(f"RJ trending topics: \n{rj_trends}")
for trend in rj_trends:
for i in trend.values():
for x in i:
if x["tweet_volume"] is not None:
if x["tweet_volume"] > 10000:
print(x["name"], x["tweet_volume"])
Example of output:
#PINKChella1Year 49997
#ConcertForBTS 108750
I have used a lot of nested for and nested if.Is there a clever way to get trending topics? The code is working but I do not know I got an error :
if x["tweet_volume"] is not None:
TypeError: string indices must be integers
How to fix it?
In this case rj_trends
is a list containing a dictionary containing a list.
So you can do this:
trends = []
for trend in rj_trends[0]['trends']:
if trend['tweet_volume'] is not None and trend['tweet_volume'] > 10000:
trends.append((trend['name'], trend['tweet_volume']))
trends.sort(key=lambda x:-x[1])
Result:
[('America', 816921),
('Felipe Neto', 117287),
('Maxon', 95250),
('Início', 88489),
('#LiveGabiMartinsEmCasa', 75254),
('#OneDirectionSave2020', 65309),
('Djonga', 64076),
('#PINKChella1year', 60945),
('TRÊS MILHÕES GIZELLYBICALHO', 42252),
('Roger', 41209),
('LUCASVIANA TE AMAMOS', 36672),
('Renan', 24669),
('Leal', 22745),
('IMUNIDADE PRA FLAY', 19824),
('ImaginaSamba', 18487),
('#BaileDoRennanDaPenhaEmCasa', 18059),
('#DennisNaFlaTV', 15938),
('Froy', 12630)]