Я пытаюсь написать рекурсивную функцию, которая может извлекать вложенные комментарии из представления 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 thread] (https://www.reddit.com/r/TrueAskReddit/comments/3g57z2/why_are_humans_fascinated_by_ascending_pertaining/) – uranther