如何将这段python代码保存为文本文件?

时间:2020-01-05 作者:Paa Amoako
# Dependencies
import json
import requests 

# Specify the URL
url = "https://official-joke-api.appspot.com/jokes/programming/ten"

# Make request and store response
r = requests.get(url)

print("Status code:", r.status_code)

response_dict = r.json()



keys = {"setup", "punchline"}
for item in response_dict:
    for key, value in item.items():
          if key in keys:
              print(key, " : ", value)
1 个回复
SO网友:cstrouse

这与主题无关,但如果您只想将设置值和punchline值写入文本文件,可以执行以下操作:

# Dependencies
import json
import requests 

# Specify the URL
url = "https://official-joke-api.appspot.com/jokes/programming/ten"

# Make request and store response
r = requests.get(url)

print("Status code:", r.status_code)

jokes = json.loads(r.text)

with open("outfile.txt", "w") as f:
    for joke in jokes:
        f.write("{}:{}\\n".format(joke["setup"], joke["punchline"]))

相关推荐

如何将多个自定义POST字段注册到json?

很抱歉,如果以前有人问过这个问题。我有几个用ACF创建的自定义字段,我正在尝试将这些字段推送到json,以便在js文件中使用它们。我的代码如下所示:function receiver_custom_fields() { foreach ( array(\'brand\', \'name\', \'cinema_dsp\') as $field ) { register_rest_field( \'receiver\', $field , array(