我正在尝试编写一个递归函数,可以从 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
s 的列表。
我错过了什么?我尽力而为——递归很难。