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

2024-04-19 06:55:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我希望能够对帖子中的评论进行迭代,直到级别n,并记录每个评论及其深度。不过,我觉得在普拉没有办法轻易做到这一点。你知道吗

我想这样做:

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]

但我不确定如何获得评论的深度。你知道吗


Tags: inforgetdefmore记录comment评论
1条回答
网友
1楼 · 发布于 2024-04-19 06:55:04

您使用post.comments.list(),PRAW文档解释了returns a flattened list of the comments。就你的目的而言,既然你关心深度,你就不要一张单子!您需要原始的未展平的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 documentation explains-请参阅以“然而,注释林可以任意深…”开头的部分。你知道吗

相关问题 更多 >