所以,我正在重写此代码,但是我正在使用Tweepy来获取趋势,我只希望10个而不是标准的50个趋势。我尝试使用网站上的其他代码(here,here和here。)并实现它,但无济于事。这是一段代码。
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"))
API.trends_place
method / API.trends_place
返回的趋势列表不一定按大多数趋势排序,因此,如果要获取前10个趋势,则必须按GET trends/place endpoint进行排序,例如:
"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)
。
另一方面,如果您只想要前50个趋势中的任何10个,则可以简单地索引已有的趋势列表,例如:
The Python Tutorial on Reading and Writing Files