2017-08-21 6 views
0

私はCrowd Tangleというソーシャルメディアサービスから統計を取得し、最初の5つの投稿の統計を出力する機能を書いています。私はループを使用して正しいJSONノードを呼び出す関数の値0から4を渡す方法を理解しようとしています。私はPython 3.6とSpyderを使用しています。関数を5回コピーして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

あなたが印刷するJSONレコードの数を表すために、あなたの関数にパラメータn_recordsを追加することができます。そして、あなたの関数では、あなたはループを作成することができます。

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

関連する問題