我试图建立一个从天气网站的api图表。我希望用户输入3个我想知道当前温度的城市,然后根据api和用户输入{name of the city - user input: the currently temp from the api}
制作一个字典,然后将字典制作成一个图{name of the city: the currently temp from the api}
我使用的api是drksky api
我主要用这个:
import matplotlib.pyplot as plt for the graph
import forecastio
import matplotlib.pyplot as plt
def read_key_from_file():
hFile = open(file_name,'r')
for line in hFile:
Mykey = line
hFile.close()
Mykey = line
return Mykey
def get_geo_location(location):
location = Nominatim().geocode(location)
lat = location.latitude
lon = location.longitude
return location, lat, lon
def comperison_graph(Mykey):
if daily_temp_dict == {}:
a = input("Enter first city name in lower case letter: ")
daily_temp_dict[a] = ""
b = input("Enter second city name in lower case letter: ")
daily_temp_dict[b] = ""
c = input("Enter third city name in lower case letter: ")
daily_temp_dict[c] = ""
for city in daily_temp_dict.keys():
location, lat, lon = get_geo_location(city)
forecast = forecastio.load_forecast(Mykey, lat, lon)
daily_temp_dict[city] = forecast.currently().temperature
data = daily_temp_dict
names = list(data.keys())
print(names)
values = list(data.values())
print(values)
plt.bar(0,values[0],tick_label=names[0])
plt.bar(1,values[1],tick_label=names[1])
plt.bar(2,values[2],tick_label=names[2])
plt.xticks(range(0,3),names)
plt.savefig('fruit.png')
plt.show()
问题是我得到的结果是这样的:
我只需要最后一个有三个城市的
不幸的是我来不了
有人能帮我吗?你知道吗
字典不是这样工作的,字典不支持append()
我想你不知道字典是怎么工作的,我建议你读一点
https://www.tutorialspoint.com/python3/python_dictionary
https://www.programiz.com/python-programming/dictionary
您应该使用空字符串
""
作为值创建一个新键:然后将
forecast
赋值给城市:注意:由于您没有提供完整的代码,它很可能不会处理错误,例如您的
get_geo_location()
没有找到一个城市。我建议您在代码中添加一些“try/catch”。你知道吗编辑:当你编辑你的问题时,这是我对你新问题的回答。你知道吗
您不应该在循环中完成所有绘图部分,而应该在循环之后完成。应该是这样的:
相关问题 更多 >
编程相关推荐