是否可以限制replace_more函数返回的一级注释?
submission.comments.replace_more(limit=1)或者从第一级删除所有MoreComments对象?我的意思是,我想限制评论树的height,并获得最大的width (从有限的第一级评论中获得所有评论)。
发布于 2020-03-11 10:26:12
在到达每个MoreComments对象时,只需替换它,而不是使用replace_more。这将防止您替换任何不在顶层的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) https://stackoverflow.com/questions/60623349
复制相似问题