2015-08-08 47 views
0

我想寫一個遞歸函數,可以從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的列表。

我錯過了什麼?我把它放在最好的位置 - 遞歸很難。

+0

[我的測試Reddit線程](https://www.reddit.com/r/TrueAskReddit/comments/3g57z2/why_are_humans_fascinated_by_ascending_pertaining/) – uranther

回答

1

你明白了。問題在於,當簡單的時候,你試圖將遞歸作爲複雜的東西。您不需要tail()函數以及map()函數,因爲您已經在遍歷評論。

我在示例中重命名了您的函數,因爲它實際上將註釋轉換爲字符串。

讓我們從簡單的案例開始,想一想:「okey,我想要一個函數,它能夠將註釋列表轉換爲字典列表」。只是簡單的功能:

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 

既然你修改你調用同一個函數,它會轉換所有回覆,不管如何他們是深刻的。希望更清楚遞歸如何工作。

+0

非常感謝。這是非常明確的,相比之下,我是如何過度複雜! – uranther