2017-08-21 86 views
0

我寫了一個函數(或試圖)從社交媒體服務獲取統計信息,稱爲Crowd Tangle,並打印出前五個帖子的統計信息。我想弄清楚如何使用循環來傳遞函數中的值0到4來調用正確的JSON節點。我正在使用Python 3.6和Spyder。而不是複製函數五次,寫入0,1,2,3,4,有沒有辦法使用循環來做到這一點?任何建議或鏈接都​​會很棒。謝謝。試圖通過循環的Python函數傳遞多個值

import requests 

def get_crowdtangle_stuff(): 
    url = 'https://api.crowdtangle.com/posts?token=mytoken' 
    json_data = requests.get(url).json() 
    #print(json_data) 

    Platform = json_data['result']['posts'][0]['platform'] 
    Platform_string = str(Platform) 
    print('This stupid thing was on the ' + Platform_string + '.') 

    Title = json_data['result']['posts'][0]['message'] 
    Title_string = str(Title) 
    print('This stupid thing was on the ' + Title_string + '.') 

    Date = json_data['result']['posts'][0]['date'] 
    Date_string = str(Date) 
    print('This stupid thing was posted on ' + Date_string) 

    Like_count = json_data['result']['posts'][0]['statistics']['actual'] 
    ['likeCount'] 
    Like_count_string = str(Like_count) 
    print('This stupid thing got ' + Like_count_string + ' likes.') 

    Shares = json_data['result']['posts'][0]['statistics']['actual'] 
    ['shareCount'] 
    Shares_string = str(Shares) 
    print('This stupid thing got ' + Shares_string + ' shares.') 

    Comments = json_data['result']['posts'][0]['statistics']['actual'] 
    ['commentCount'] 
    Comments_string = str(Comments) 
    print('This stupid thing got ' + Comments_string + ' comments.') 

    Wow_count = json_data['result']['posts'][0]['statistics']['actual'] 
    ['wowCount'] 
    Wow_count_string = str(Wow_count) 
    print('This stupid thing got ' + Wow_count_string + ' wows.') 

    Total_engagement = Like_count + Shares + Comments + Wow_count 
    Total_engagement_string = str(Total_engagement) 
    print('This stupid things total engagement score is ' + 
    Total_engagement_string + '.') 

    Link = json_data['result']['posts'][0]['link'] 
    Link_string = str(Link) 
    print('This stupid thing has a link of ' + Link_string + '.') 

get_crowdtangle_stuff() 

回答

2

您可以將參數n_records添加到您的函數來表示數量的JSON記錄要打印。然後在你的功能,你可以創建一個循環:

for n in range(n_records): 
    ...Rest of your code here where you can use n to retrieve the JSON record and print the outputs your want... 

然後你就可以輸入一個數字來表示你要多少條記錄,當你調用該函數來打印,即:

get_crowdtangle_stuff(5) 
+0

那完美。謝謝! – Eric