3

openweather と json 形式を使用して、Python で気象条件を取得する簡単なコードを見つけて変更しました。しかし、問題があります。都市が間違っているとどのように言えますか?

つまり、間違った存在しない都市を通過しても、 read は常に答えを返します (「空の応答」などはありません)。

私が話していることを確認するには、以下のコードを参照してください。

#!/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!
4

1 に答える 1

1

要求された都市が存在しない場合、繰り返し ID があります。コードをそれに基づいて作成するか、2 番目の要求を行うことができます。私が使用したであろう2つの解決策を説明しました。

#!/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"
于 2012-12-07T17:15:34.567 に答える