Python and Weather.com
Fazer
faizans at gmail.com
Thu Aug 12 23:17:21 EDT 2004
Hello,
I made a small python script that gives the current weather conditions
of a city that you give as an argument. Here's the basic function
behind it:
I am really a beginnering when it comes to parsing XML but I just used
split to get the values I wanted. Any ideas how I can use proper XML
parsing techniques?
Also, the weather degree is in celcius but I conver it to fahrenheit
as well. :-)
Here's the code:
# Get the weather for the city specified
def get_weather(city):
#city = city.replace(" ", "%20")
w = urllib.urlopen("http://xoap.weather.com/search/search?where=%s" %
city.replace(" ", "%20")).read()
# Check if there were matches
if not city.isalpha() or w.find("loc") < 0:
return "No matches found for city of " + city + "!"
# If so, use the first search result and use it
city = w.split("</loc>", 1)[0].split("<loc")[1].split(">")[1]
# Get location id of the first city
locid = w.split("</loc>", 1)[0].split("<loc")[1].split('"', 2)[1]
# Get weather readings
weather = urllib.urlopen("http://xoap.weather.com/weather/local/%s?cc=*&prod=xoap&par=xxx&key=xxx&unit=m"
%
locid).read()
# Get conditions
reading = weather.split("</t>")[0].split("<t>")[1]
# Get temperature
temp = weather.split("</tmp>")[0].split("<tmp>")[1]
if "N/A" in temp:
return "Error"
else:
temp = int(temp)
return "Weather for %s is %s C / %s F and %s" % (city,temp,(temp *
1.8) + 32,reading)
Hope it helps anyone out there. Please feel free to fix anything I
may have done wrong. Comments greatly appreciated!
Thanks,
Faizan S.
More information about the Python-list
mailing list