不过,我对这一切都很陌生。在我的代码中,我试图让 Python 从一些免费的天气 API 中获取天气信息。然而,一切都会按计划进行,它会得到天气 - 晴天,但是当涉及到整数时它会吓坏,并且所需的大部分信息都是整数:温度、湿度、风速等。这就是它的地方失败:
for result in data['main']:
temp = result['temp']
print('Temperature: '+temp)
with open('data.txt', 'a') as f:
f.write(' '+temp)
f.write('\n')
该表如下所示:
'main': {'feels_like': 304.72,
'humidity': 67,
'pressure': 1011,
'temp': 301.84,
'temp_max': 303.85,
'temp_min': 299.19},
主要是字典。
我试过添加[3]
而不是['temp'\]
for result in data['main']:
temp = result[3]
print('Temperature: '+temp)
with open('data.txt', 'a') as f:
f.write(' '+temp)
f.write('\n')
但是,输出是每个类别的前 3 个字母,例如TEM
- TEMP / HUM
- HUMIDITY
我知道它做了什么,但我只是信任某个网站。我不知道有什么方法可以解决这个问题,很多网站只是声明“更改 JSON 文件”,但我真的做不到。
我试过“Json.Loads”,但它指出,必须是“str、bytes 或 bytearray,而不是 dict”。
追溯
File "location", line 30, in <module>
temp = result['temp']
TypeError: string indices must be integers
你的代码:
for result in data['main']:
temp = result[3]
print('Temperature: '+temp)
with open('data.txt', 'a') as f:
f.write(' '+temp)
f.write('\n')
遍历 data['main'] 的键值。换句话说,每个循环result
都是列表中的一个值["feels_like", "humidity", "pressure", "temp", "temp_max", "temp_min"]
你真正想做的事:
for result in data["main"]:
if result == "temp":
print("Temperature: %0.2f" % data["main"][result])
with open("data.txt", "a") as f:
f.write(" %0.2f\n" % data["main"][result])
甚至:
for field, result in data["main"].items():
if field == "temp":
print("Temperature: %0.2f" % result)
with open("data.txt", "a") as f:
f.write(" %0.2f\n" % result)
它从字典中获取键和值data["main"]
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句