繁体   English   中英

如何在PRAW中存储评论的深度?

[英]How to store a comment's depth in PRAW?

我希望能够遍历n级之前的帖子中的评论,并记录每个评论及其深度。 不过,我认为没有办法在Praw轻松做到这一点。

我想做这样的事情:

def get_post_comments(post, comment_limit):
  comments = []
  post.comments.replace_more(limit=comment_limit)
  for comment in post.comments.list():
    # do something 

  return [comment.body, comment_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

另外,您可以按照PRAW文档的说明进行广度优先遍历而无需递归(我们也可以进行深度优先而不递归,显式使用堆栈),请参见以“但是,注释林可以任意深……”。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM