[英]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.