Skip to content

Instantly share code, notes, and snippets.

@kylecorry31
Created January 7, 2015 23:45
Show Gist options
  • Save kylecorry31/0b060d69cd0547c63bca to your computer and use it in GitHub Desktop.
Save kylecorry31/0b060d69cd0547c63bca to your computer and use it in GitHub Desktop.
import urllib.request, urllib.parse, json
def getWeatherInfo(zipcode):
"""Takes a zipcode (str) that is passed to Yahoo Weather API and returns
an array of dictionaries and a string in this format:
[current_weather (dict), forecasts (dict), title (str)].
Keys include: day, date, high, low, text, temp.
"""
baseurl = "https://query.yahooapis.com/v1/public/yql?"
yql_query = "select item from weather.forecast where woeid in" + " (select woeid from geo.places(1) where text='" + zipcode + "')"
yql_url = baseurl + urllib.parse.urlencode({'q':yql_query}) + "&format=json"
result = urllib.request.urlopen(yql_url).read()
data = json.loads(result.decode("utf-8"))
title = data['query']['results']['channel']['item']['title']
current = data['query']['results']['channel']['item']['condition']
forecasts = data['query']['results']['channel']['item']['forecast']
return [current, forecasts, title]
def printWeather(info):
print()
print(info[2])
print('-'*60+'\n')
print("Current conditions:", info[0]['temp'] + '°F --', info[0]['text'])
print("Today's forecast:", 'High:', info[1][0]['high'] + '°F', 'Low:', info[1][0]['low'] + '°F --', info[1][0]['text'] + '\n')
print("Forecast:")
for forecast in info[1][1:]:
print(forecast['day'] + ',', forecast['date'], '--', 'High:',
forecast['high'] + '°F', 'Low:', forecast['low'] + '°F --',
forecast['text'])
print()
if __name__ == '__main__':
code = input("Enter a zipcode: ")
info = getWeatherInfo(code)
printWeather(info)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment