是否可以限制replace_more
函数返回的第一级注释?
submission.comments.replace_more(limit=1)
还是MoreComments
从第一级删除所有对象?我的意思是我想限制评论树height
并获得最大的width
评论(从有限数量的第一级评论中获取所有评论)。
不必使用replace_more
,而只需替换每个MoreComments
对象即可。这将防止您替换MoreComments
不在顶层的任何对象。
下面是一个函数,它将遍历顶级注释,MoreComments
并在遇到每个注释时将其替换。这是受到PRAW文档中示例代码的启发:
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)