#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"])
输出示例:
#PINKChella1Year 49997
#ConcertForBTS 108750
我使用了大量的for和nested if。是否有一种巧妙的方法来获取热门话题?该代码正在工作,但我不知道我遇到了错误:
if x["tweet_volume"] is not None:
TypeError: string indices must be integers
如何解决?
在这种情况下,rj_trends
是包含列表的字典。
所以您可以这样做:
for trend in rj_trends[0]['trends']:
if trend['tweet_volume'] is not None and trend['tweet_volume'] > 10000:
print(trend['name'], trend['tweet_volume'])
结果:
#BaileDoRennanDaPenhaEmCasa 18059
#LiveGabiMartinsEmCasa 75254
ImaginaSamba 18487
TRÊS MILHÕES GIZELLYBICALHO 42252
Djonga 64076
Renan 24669
Maxon 95250
Felipe Neto 117287
#DennisNaFlaTV 15938
Início 88489
Roger 41209
America 816921
LUCASVIANA TE AMAMOS 36672
Froy 12630
IMUNIDADE PRA FLAY 19824
Leal 22745
#OneDirectionSave2020 65309
#PINKChella1year 60945