如何限制Praw Reddit 的一级评论?
How to limit first level comments in Praw Reddit?
是否可以限制 replace_more
功能 returns 的一级评论?
submission.comments.replace_more(limit=1)
或者从第一层移除所有 MoreComments
个对象?我的意思是我想限制评论树 height
并获得最大值 width
(获取所有来自有限数量的第一级评论的评论)。
而不是使用 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)
是否可以限制 replace_more
功能 returns 的一级评论?
submission.comments.replace_more(limit=1)
或者从第一层移除所有 MoreComments
个对象?我的意思是我想限制评论树 height
并获得最大值 width
(获取所有来自有限数量的第一级评论的评论)。
而不是使用 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)