我想寫一個遞歸函數,可以從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
的列表。
我錯過了什麼?我把它放在最好的位置 - 遞歸很難。
[我的測試Reddit線程](https://www.reddit.com/r/TrueAskReddit/comments/3g57z2/why_are_humans_fascinated_by_ascending_pertaining/) – uranther