【发布时间】:2021-05-07 19:05:22
【问题描述】:
(用于不和谐机器人的异步 Python 内容)
通过asyncpraw使用reddit API
我正在调用 reddit API 并返回 subreddit 的十个热门帖子。
hot_posts = returned_subreddit.hot(limit=10)
打印<asyncpraw.models.listing.generator.ListingGenerator object at 0x0000021B3CC1A3A0>
这个对象可以被迭代,并且可以使用不同的属性。例如:
async for submission in hot_posts:
print(submission.title)
print(submission.score)
print(submission.id)
print(submission.url)
我想知道如何从这个生成器对象中选择一个随机提交。我的目标是让我的不和谐机器人发送消息以响应命令。该消息将包含指向给定 subreddit 上十大热门帖子之一的链接。
我尝试通过索引访问它,例如hot_posts[3] 扔了 TypeError: 'ListingGenerator' object is not subscriptable
目前使用random 库尝试过:
choice(hot_posts)
结果:TypeError: object of type 'ListingGenerator' has no len()
random.sample(hot_posts, k=1)
结果:TypeError: Population must be a sequence. For dicts or sets, use sorted(d).
文档:
https://asyncpraw.readthedocs.io/en/latest/code_overview/models/subreddit.html
【问题讨论】:
标签: python random generator python-asyncio praw