gpt4 book ai didi

Python openweather, json - 按城市名称获取天气 - 我怎么能说城市不正确?

转载 作者:行者123 更新时间:2023-11-28 18:50:28 25 4
gpt4 key购买 nike

我找到并修改了简单的代码,以使用 openweather 和 json 格式在 Python 中获取天气状况。但是我有一个问题——我怎么能说这个城市是不正确的呢?

我的意思是,即使我经过了一个错误的、不存在的城市,阅读也总是会给出答案(没有“空洞的回应”之类的东西)。

请参阅下面的代码以了解我在说什么:

#!/usr/bin/python
# -*- coding: utf-8 -*-
import urllib2, json

city = "etre4t5r5e4re" # the city name is incorrent
url = "http://openweathermap.org/data/2.1/forecast/city?q="
url += city
try :
request = urllib2.Request(url)
response = urllib2.urlopen(request)
except urllib2.HTTPError, e:
info = wx.MessageBox(u"Internet connection error", u"Error", wx.OK | wx.ICON_ERROR)
except urllib2.URLError, e:
info = wx.MessageBox(u"Internet connection error", u"Error", wx.OK | wx.ICON_ERROR)
except httplib.HTTPException, e:
info = wx.MessageBox(u"Internet connection error", u"Error", wx.OK | wx.ICON_ERROR)
except Exception:
info = wx.MessageBox(u"Error", u"Error", wx.OK | wx.ICON_ERROR)
weather = response.read()

if __name__ == '__main__':
print(weather) # it will show weather but thats not what I want for non-existing city!

最佳答案

当所请求的城市不存在时,会出现一个循环 ID,您可以基于该 ID 编写代码,或者进行第二次请求。我已经解释了我会使用的两种解决方案。

#!/usr/bin/python

import urllib2, json

city = "etre4t5r5e4re"
root = "http://openweathermap.org/data/2.1/forecast/city?q=%s"
url = root % city

response = urllib2.urlopen(url)
j = json.load(response)

# Solution 1
if j.get('url', '').split('/')[-1] == '7284885':
print " ! This city seems to be THE Unknown city"

# Solution 2
if 'No station' in urllib2.urlopen(j.get('url')).read():
print " ! Again.. This city seems to be THE Unknown city"

关于Python openweather, json - 按城市名称获取天气 - 我怎么能说城市不正确?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13761612/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com