如何在Praw Reddit中限制第一级评论?

问题描述 投票:0回答:1

是否可以限制replace_more函数返回的第一级注释?

submission.comments.replace_more(limit=1)

或从第一级中删除所有MoreComments对象?我的意思是我想限制评论树height并获得最大width(获取所有来自第一层评论数量有限的评论)。

python reddit praw
1个回答
0
投票

而不是使用replace_more,只需替换每个MoreComments对象即可。这将防止您替换任何不在顶层的MoreComments对象。

下面是一个函数,它将循环访问顶级注释,并在遇到每个MoreComments时将其替换。这是受example code from the PRAW documentation的启发:

from praw.models import MoreComments

def iter_top_level(comments):
    for top_level_comment in comments:
        if isinstance(top_level_comment, MoreComments):
            yield from iter_top_level(top_level_comment.comments())
        else:
            yield top_level_comment

此生成器的工作方式是从提交中生成顶级注释,但是当遇到MoreComments对象时,它将加载这些注释并递归调用自身。递归调用是必需的,因为在大线程中,每个MoreComments对象在末尾都包含另一个顶级MoreComments对象。

这里是如何使用它的示例:

submission = reddit.submission('fgi5bd')
for comment in iter_top_level(submission.comments): 
    print(comment.author) 
© www.soinside.com 2019 - 2024. All rights reserved.