Python 如何存储评论';普拉夫有多深?

Python 如何存储评论';普拉夫有多深?,python,reddit,praw,Python,Reddit,Praw,我希望能够在一篇文章中重复评论到n,并记录每个评论及其深度。不过,我认为在普拉没有办法轻易做到这一点 我想做这样的事情: def get_post_注释(post,comment_limit): 评论=[] post.comments.replace\u more(limit=comment\u limit) 对于post.comments.list()中的注释: #做点什么 返回[comment.body,comment\u depth] 但我不确定如何获得评论的深度 您可以使用post.c

我希望能够在一篇文章中重复评论到
n
,并记录每个评论及其深度。不过,我认为在普拉没有办法轻易做到这一点

我想做这样的事情:

def get_post_注释(post,comment_limit):
评论=[]
post.comments.replace\u more(limit=comment\u limit)
对于post.comments.list()中的注释:
#做点什么
返回[comment.body,comment\u depth]

但我不确定如何获得评论的深度

您可以使用
post.comments.list()
,PRAW文档对此进行了解释。出于您的目的,因为您关心深度,所以您不想要一个简单的列表!您需要原始的未展平的
CommentForest

使用递归,我们可以使用生成器通过深度优先遍历访问此林中的注释:

def process_comment(comment, depth=0):
    """Generate comment bodies and depths."""
    yield comment.body, depth
    for reply in comment.replies:
        yield from process_comment(reply, depth + 1)

def get_post_comments(post, more_limit=32):
    """Get a list of (body, depth) pairs for the comments in the post."""
    comments = []
    post.comments.replace_more(limit=more_limit)
    for top_level in post.comments:
        comments.extend(process_comment(top_level))
    return comments
或者,您可以在不递归的情况下执行广度优先遍历(我们也可以在不递归的情况下执行深度优先遍历,显式使用堆栈),如-请参阅以“然而,注释林可以任意深…”开头的部分