是否可以限制replace_more
函数返回的第一级注释?
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)