试图通过循环的Python函数传递多个值
问题描述:
我写了一个函数(或试图)从社交媒体服务获取统计信息,称为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()
答
您可以将参数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)
那完美。谢谢! – Eric