/ Published in: Python
Expand |
Embed | Plain Text
#!/usr/bin/env python #-*- coding:utf-8 -*- # Copyright 2009 Grigor Kolev <grigor.kolev@gmail.com> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, # MA 02110-1301, USA. #---------------------------------------------------------------------------------------------------------- # These functions are taken from the module pywapy. # Created by Eugene Kaznacheev <qetzal@gmail.com> #---------------------------------------------------------------------------------------------------------- import urllib2, re from xml.dom import minidom from urllib import quote GOOGLE_WEATHER_URL = 'http://www.google.com/ig/api?weather=%s&hl=%s' GOOGLE_COUNTRIES_URL = 'http://www.google.com/ig/countries?output=xml&hl=%s' GOOGLE_CITIES_URL = 'http://www.google.com/ig/cities?output=xml&country=%s&hl=%s' def get_weather_from_google(location_id, hl = ''): """ Fetches weather report from Google Parameters location_id: a zip code (10001); city name, state (weather=woodland,PA); city name, country (weather=london, england); latitude/longitude(weather=,,,30670000,104019996) or possibly other. hl: the language parameter (language code). Default value is empty string, in this case Google will use English. Returns: weather_data: a dictionary of weather data that exists in XML feed. """ location_id, hl = map(quote, (location_id, hl)) url = GOOGLE_WEATHER_URL % (location_id, hl) handler = urllib2.urlopen(url) content_type = handler.info().dict['content-type'] charset = re.search('charset\=(.*)',content_type).group(1) if not charset: charset = 'utf-8' if charset.lower() != 'utf-8': xml_response = handler.read().decode(charset).encode('utf-8') else: xml_response = handler.read() dom = minidom.parseString(xml_response) handler.close() weather_data = {} weather_dom = dom.getElementsByTagName('weather')[0] data_structure = { 'forecast_information': ('city', 'postal_code', 'latitude_e6', 'longitude_e6', 'forecast_date', 'current_date_time', 'unit_system'), 'current_conditions': ('condition','temp_f', 'temp_c', 'humidity', 'wind_condition', 'icon') } for (tag, list_of_tags2) in data_structure.iteritems(): tmp_conditions = {} for tag2 in list_of_tags2: try: tmp_conditions[tag2] = weather_dom.getElementsByTagName(tag)[0].getElementsByTagName(tag2)[0].getAttribute('data') except IndexError: pass weather_data[tag] = tmp_conditions forecast_conditions = ('day_of_week', 'low', 'high', 'icon', 'condition') forecasts = [] for forecast in dom.getElementsByTagName('forecast_conditions'): tmp_forecast = {} for tag in forecast_conditions: tmp_forecast[tag] = forecast.getElementsByTagName(tag)[0].getAttribute('data') forecasts.append(tmp_forecast) weather_data['forecasts'] = forecasts dom.unlink() return weather_data def get_country_from_google(hl = ''): """ Get list of countries in specified language from Google Parameters hl: the language parameter (language code). Default value is empty string, in this case Google will use English. Returns: countries: a list of elements(all countries that exists in XML feed). Each element is a dictionary with 'name' and 'iso_code' keys. For example: [{'iso_code': 'US', 'name': 'USA'}, {'iso_code': 'FR', 'name': 'France'}] """ url = GOOGLE_COUNTRIES_URL % hl handler = urllib2.urlopen(url) content_type = handler.info().dict['content-type'] charset = re.search('charset\=(.*)',content_type).group(1) if not charset: charset = 'utf-8' if charset.lower() != 'utf-8': xml_response = handler.read().decode(charset).encode('utf-8') else: xml_response = handler.read() dom = minidom.parseString(xml_response) handler.close() countries = [] countries_dom = dom.getElementsByTagName('country') for country_dom in countries_dom: country = {} country['name'] = country_dom.getElementsByTagName('name')[0].getAttribute('data') country['iso_code'] = country_dom.getElementsByTagName('iso_code')[0].getAttribute('data') countries.append(country) dom.unlink() return countries def get_cities_from_google(country_code, hl = ''): """ Get list of cities of necessary country in specified language from Google Parameters country_code: code of the necessary country. For example 'de' or 'fr'. hl: the language parameter (language code). Default value is empty string, in this case Google will use English. Returns: cities: a list of elements(all cities that exists in XML feed). Each element is a dictionary with 'name', 'latitude_e6' and 'longitude_e6' keys. For example: [{'longitude_e6': '1750000', 'name': 'Bourges', 'latitude_e6': '47979999'}] """ url = GOOGLE_CITIES_URL % (country_code.lower(), hl) handler = urllib2.urlopen(url) content_type = handler.info().dict['content-type'] charset = re.search('charset\=(.*)',content_type).group(1) if not charset: charset = 'utf-8' if charset.lower() != 'utf-8': xml_response = handler.read().decode(charset).encode('utf-8') else: xml_response = handler.read() dom = minidom.parseString(xml_response) handler.close() cities = [] cities_dom = dom.getElementsByTagName('city') for city_dom in cities_dom: city = {} city['name'] = city_dom.getElementsByTagName('name')[0].getAttribute('data') city['latitude_e6'] = city_dom.getElementsByTagName('latitude_e6')[0].getAttribute('data') city['longitude_e6'] = city_dom.getElementsByTagName('longitude_e6')[0].getAttribute('data') cities.append(city) dom.unlink() return cities #--------------------------------------------------------------------------------------------- class Error(Exception): #Създава мое изключение def __init__(self, value): #Конструктор създава инстанция стоиност на инстанция по подразбиране при извикване на класа self.value = value def Value(self ): #Връща резултат на стоиноста на инстанцията return self.value class BadCountryCode(Error): pass class BadSityName (Error): pass class Country (): ''' Take the Countri list with country code. ''' def __init__(self): self.data = get_country_from_google() a = 0 tmp = {} for i in self.data: a +=1 tmp[a] = i self.data = tmp def show(self ): for i in self.data.values(): print '\n' for keys in i.keys(): print keys, '.'*10, i[keys] def get(self ): return self.data class Sity (Country): def __init__(self, country_code = None): try: self.data = get_cities_from_google(country_code) tmp = {} a = 0 for i in self.data: a+=1 tmp[a] = i.get('name') self.data = tmp if len(self.data) == 0: raise BadCountryCode, 'Invalid country code. You can see all available iso_code with: country = Country() country.show()' except AttributeError: print 'You must select country code \nYou can see all available iso_code with: \ncountry = Country() \ncountry.show()' def show(self): for keys in self.data.keys(): print keys,'.'*10, self.data.get(keys) class Weather (Sity): def __init__(self, sity_name = None): try: self.data = get_weather_from_google(sity_name) tmp = {} tmp['Sity'] = (sity_name) tmp['temp_c'] = self.data.get('current_conditions').get('temp_c') tmp['temp_f'] = self.data.get('current_conditions').get('temp_f') self.data = tmp if self.data['temp_c'] == None: raise BadSityName, 'Wrong or not available on a city name. You can see all available sity with: sity = Sity() sity.show()' except TypeError: print 'You must write the name of the sity.\nYou can see all available sity with:\nsity = Sity()\nsyty.show()' if __name__ == '__main__': weather = Weather('Varna') weather.show() raw_input()
You need to login to post a comment.
