简体   繁体   English

如何从 subreddit 中获取随机帖子(praw)

[英]How to fetch a random post from a subreddit (praw)

I have a question:我有个问题:

What would be an easy way to get a random post of a subreddit?获取 subreddit 随机帖子的简单方法是什么? Or best if I could get a random post made within 24 hours.或者最好是我能在 24 小时内收到一个随机的帖子。

In older versions of praw, you could use在旧版本的 praw 中,您可以使用

sub = r.get_subreddit('earthporn')
posts = sub.get_random_submission() 
print(posts.url)

However "get_random_submission" doesn't exist anymore.但是“get_random_submission”不再存在。 I know I could use something like我知道我可以使用类似的东西

sub = r.subreddit('all')
    for posts in sub.hot(limit=20):
        random_post_number = random.randint(0,20)
        for i,posts in enumerate(sub.hot(limit=20)):
            if i==random_post_number:
                print(posts.score)

But this is very buggy and not power efficient.但这非常有问题,而且不节能。 Plus I'm using this for a twitter bot, and I get an error after like 5 minutes with this code.另外,我将它用于 twitter 机器人,使用此代码大约 5 分钟后出现错误。

So I would really like to know if there's an easy way to get a random post of submission, and if I could get that random submission within a certain timeframe (such as the last 24 hours)?所以我真的很想知道是否有一种简单的方法可以获得随机提交的帖子,以及我是否可以在特定时间范围内(例如过去 24 小时)获得该随机提交?

Thanks!谢谢!

You could simplify your code more than so and avoid the double loop.您可以更简化您的代码并避免双循环。

sub = r.subreddit('all')
posts = [post for post in sub.hot(limit=20)]
random_post_number = random.randint(0, 20)
random_post = posts[random_post_number]

You can get a random post by generating a number and then getting that post from a list.您可以通过生成一个数字然后从列表中获取该帖子来获得随机帖子。 When it comes to selecting only posts from the last 24 hours you will need to fill an array with those posts first.当只选择过去 24 小时内的帖子时,您需要先用这些帖子填充数组。 I compare the current time with the time the post was submitted, if it is less than 24 hours I add it to the list posts .我将当前时间与提交帖子的时间进行比较,如果不到 24 小时,我会将其添加到列表posts

It is from the list then that you can take a random submission out to do whatever you choose to do.然后,您可以从列表中随机提交一份文件来做您选择做的任何事情。 This submission I have named random_post .我将此提交命名为random_post

import praw
import time
import random


LIMIT_POST = 5

subreddit = reddit.subreddit('all')
new_submissions = subreddit.new(limit = LIMIT_POST)

current_time = int(time.time())

posts = []

for submission in new_submissions:
        sub_age = ((current_time - submission.created_utc) /60 /60 /24)
        if sub_age < 1:
                posts.append(submission)


random_number = random.randint(0,LIMIT_POST -1)
random_post = posts[random_number]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM