python - 你能用 tweepy 只询问 10 个趋势吗?
问题描述
所以,我正在重写这个,但我使用 Tweepy 来获取趋势,我只想要 10 个,而不是标准的 50 个趋势。我曾尝试使用网站上的其他代码(此处、此处和此处。)并实施它,但无济于事。这是一段代码。
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
方法/ GET 趋势/地点端点返回的趋势列表不一定按最流行的顺序排列,因此如果您想获得前 10 个趋势,则必须按 排序"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)
请注意,正如您链接的 Stack Overflow 问题的答案和评论所指出的那样,在您的代码段中泄漏文件对象是一种不好的做法。请参阅有关读取和写入文件的 Python 教程。
另一方面,如果您只是想要前 50 个趋势中的任何 10 个,您可以简单地索引您已经拥有的趋势列表,例如:
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)
推荐阅读
- tensorflow - Custom metrics for image segmentation in Keras
- python - 当我尝试导入名为 urlib 的模块时,powershell 中的 Python 给了我一个导入错误
- javascript - 如何使用钩子更新后加载反应值
- regex - 具有 .00 数字格式的正则表达式范围
- openldap - 如何将openldap服务器中具有pwdchangedtime的用户导出到另一个openldap服务器
- html - 使用 CSS 标记的自定义文本
- prolog - 从列表中获取一组元素(Prolog)
- spring-boot - Kotlin 协程观察者
- flutter - 如何保存 TextField 用户输入
- javascript - 当项目有键时 Firebase 更新或添加值