我正在创建一个Python程序,它将向我发送我最喜欢的Subreddits帖子的前十个列表。目前代码如下:
def AskReddit():
askReddit = requests.get('http://www.reddit.com/r/AskReddit/top.json',
headers={'user-agent':'Mozilla/5.0'},
auth=('TadaceAce','Password'),
)
n = 0
for post in askReddit.json()['data']['children']:
x[n] = post['data']['title']
n += 1
if (n == 10):
break
output = "{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}".format(x[0],
x[1], x[2], x[3],
x[4], x[5], x[6],
x[7], x[8], x[9])
return output
def todayILearned():
todayilearned = requests.get('http://www.reddit.com/r/todayilearned/top.json',
headers={'user-agent':'Mozilla/5.0'},
auth=('TadaceAce','Password'),
)
n = 0
for post in todayilearned.json()['data']['children']:
x[n] = post['data']['title']
n += 1
if (n == 5):
break
output = "{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}".format(x[0],
x[1], x[2], x[3],
x[4], x[5], x[6],
x[7], x[8], x[9])
return output
我正在尝试干燥代码,因为我将添加越来越多的子项,但我被这段代码卡住了:
def reddit(subreddit):
todayilearned = requests.get('http://www.reddit.com/r/{}/top.json'.format(subreddit),
headers={'user-agent':'Mozilla/5.0'},
auth=('TadaceAce','Password'),
)
z = "%s.json" % subreddit
n = 0
for post in z()['data']['children']:
x[n] = post['data']['title']
n += 1
if (n == 5):
break
output = "{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}".format(x[0],
x[1], x[2], x[3],
x[4], x[5], x[6],
x[7], x[8], x[9])
return output
你要怎么解决这个问题?特别是for循环,因为我80%确定这就是问题所在。你知道吗
这里的问题是 ^方法}
reddit(subreddit)
中的{z
是一个字符串,您将其用作可调用对象。你知道吗据我所知你需要做的是
z = todayilearned.json()
如果您能够从url获取数据,并且如果json具有
data
和children
属性,并且x
应该被初始化,那么这应该可以工作正如我在上面的评论中提到的,你的代码似乎有点随意,我也注意到你说你得到了一个前十名列表,然后你在输出中使用了10个x元素,但是你在6之后打破了for循环。你知道吗
下面的函数应该满足您的实际要求。你知道吗
调用
print(reddit('AskReddit'))
返回相关问题 更多 >
编程相关推荐