递归检索线程评论列表

Retrieving a threaded comment list recursively

我正在尝试编写一个可以从 Reddit 提交中检索嵌套评论的递归函数。我正在使用 Python + PRAW

def _get_comments(comments, ret = []):
    for comment in comments:
        if len(comment._replies) > 0:
            return _get_comments(tail(comments), ret + [{
                #"body": comment.body,
                "id": comment.id,
                "author": str(comment.author),
                "replies": map(lambda replies: _get_comments(replies, []), [comment._replies])
                }])
        else:
            return ret + [{
                    #"body": comment.body,
                    "id": comment.id,
                    "author": str(comment.author)
                }]
    return ret

def tail(list):
    return list[1:len(list)]

我得到以下输出,它不完整并且包含嵌套数组:

pprint(_get_comments(s.comments))
[{'author': 'wheremydirigiblesat',
  'id': u'ctuzo4x',
  'replies': [[{'author': 'rhascal',
                'id': u'ctvd6jw',
                'replies': [[{'author': 'xeltius', 'id': u'ctvx1vq'}]]}]]},
 {'author': 'DemiDualism',
  'id': u'ctv54qs',
  'replies': [[{'author': 'rhascal',
                'id': u'ctv5pm1',
                'replies': [[{'author': 'blakeb43', 'id': u'ctvdb9c'}]]}]]},
 {'author': 'Final7C', 'id': u'ctvao9j'}]

Submission 对象有一个 comments 属性,它是 Comment 对象的列表。每个 Comment 对象都有一个 _replies 属性,它是更多 Comment 的列表。

我错过了什么?我尽力了——递归很难。

你几乎答对了。问题是当递归很简单时,您试图将其复杂化。您不需要内部的 tail() 函数和 map() 函数,因为您已经在遍历注释。

我在示例中重命名了您的函数,因为它实际上将注释转换为字典。

让我们从简单的案例开始,这样想:"okey, I want to have a function, which is able to convert list of comments to list of dicts"。只是简单的功能:

def comments_to_dicts(comments):
    results = []  # create list for results
    for comment in comments:  # iterate over comments
        item = {
            "id": comment.id,
            "author": comment.author,
        }  # create dict from comment

        results.append(item)  # add converted item to results 
    return results  # return all converted comments

现在您希望字典还包含转换为字典的回复列表。而且你已经有了能够进行这种转换的函数,所以让我们使用它并将结果放入 item['replies']:

def comments_to_dicts(comments):
    results = []  # create list for results
    for comment in comments:  # iterate over comments
        item = {
            "id": comment.id,
            "author": comment.author,
        }  # create dict from comment

        if len(comment._replies) > 0:
            item["replies"] = comments_to_dicts(comment._replies)  # convert replies using the same function

        results.append(item)  # add converted item to results 
    return results  # return all converted comments

由于您修改了您调用的同一个函数,它会转换所有回复,无论它们有多深。希望它更清楚递归是如何工作的。