Как разобрать сложный список, имеющий внутри неограниченный словарь и список - PullRequest
0 голосов
/ 08 декабря 2018

У меня есть функция, которая возвращает комментарии Reddit и их ответы до n-уровней, я сталкиваюсь с трудностями, как я могу извлечь комментарии и реплики и сохранить их в CSV.Функция следующая и вывод также записывается

def comments_to_dicts(comments):
    results = []  
    for comment in comments:  
        item = {
            "id": comment.id,
            "author": comment.author,
            "up votes": comment.ups,
            "comment-text":comment.body,
        }         
        if len(comment._replies) > 0:
            item["replies"] = comments_to_dicts(comment._replies)
        results.append(item)   
    return results

это вывод, я просто отображаю только один.

[{'id': 'e5bpnup', 'author': Redditor(name='AnxiousSun'), 'up votes': 38, 'comment-text': 'Maps is getting way too bloated and uses way too much rich-media. The explore tab could be its own app. ', 'replies': [{'id': 'e5bu127', 'author': Redditor(name='baspeysp'), 'up votes': 9, 'comment-text': 'Way too bloated, I only use it to locate a place but rarely to do anything about the location, got better apps for that. ', 'replies': [{'id': 'e5c2txt', 'author': Redditor(name='YupSuprise'), 'up votes': 3, 'comment-text': "I haven't heard of any apps for that, mind dropping some recommendations? ", 'replies': [{'id': 'e5chm3o', 'author': Redditor(name='moralesnery'), 'up votes': 2, 'comment-text': "maybe he's talking about another GPS Navigation APP?\n\nIf that's the case we have HERE We Go, Sygic, Tom-Tom, Karta, MAPS.ME, OsmAnd, etc."}]}, {'id': 'e5d9oa2', 'author': Redditor(name='jojo_31'), 'up votes': 1, 'comment-text': 'Yeah me too, the maps themselves kind of suck, rather use OsmAnd'}]}]}]

1 Ответ

0 голосов
/ 08 декабря 2018

Вместо добавления ответов на новый ключ в словаре, вы должны добавить их как отдельные элементы списка results.Это сгладит иерархическую структуру, чтобы вы могли сохранить ее как CSV.

def comments_to_dicts(comments, parentid = 0):
    results = []  
    for comment in comments:  
        item = {
            "id": comment.id,
            "author": comment.author,
            "up votes": comment.ups,
            "comment-text": comment.body,
            "in-reply-to": parentid
        }         
        results.append(item)
        for reply in comment._replies:
            results += comments_to_dicts(reply, comment.id)
    return results

Я добавил поле in-reply-to к диктофонам, чтобы вы могли восстановить иерархию из CSV.

...