Get Weather!

Code-Stücke können hier veröffentlicht werden.
Antworten
Dav1d
User
Beiträge: 1437
Registriert: Donnerstag 30. Juli 2009, 12:03
Kontaktdaten:

snafu hat geschrieben:Welche Liste? Meinst du das Wörterbuch mit den Tupeln? Warum soll es umständlicher sein, eine Liste zu benutzen als etwas zu zerlegen? Aber kann ja gut sein, dass man manche Schritte noch vereinfachen kann. Habe das nach bestem Wissen und Gewissen strukturiert. ;)
Ah, stimmt, die Liste war in den alten 'Versionen'
the more they change the more they stay the same
Dav1d
User
Beiträge: 1437
Registriert: Donnerstag 30. Juli 2009, 12:03
Kontaktdaten:

Ich hab das komplette Skript nochmal überarbeitet, diesmal wird lxml oder BeautifulSouo verwendet, welches gerade installiert ist!

Code: Alles auswählen

#!/usr/bin/python
# -*- coding: utf-8 -*-

import sys
if sys.version_info[0] < 3:
    import urllib2 as ulib
else:
    import urllib.request as ulib

try:
    from lxml import etree
    parser = 'etree'
except ImportError:
    try:
        from BeautifulSoup import BeautifulStoneSoup
        parser = 'beautifulstonesoup'
    except ImportError:
        raise ImportError('lxml or BeautifulSoup must be installed')

langs = {'german' : 'de',
         'french' : 'fr',
         'english' : 'en',
         'de' : 'de',
         'fr' : 'fr',
         'en' : 'en'}
          

def get_weather(location, lang):
    '''parses a XML-Document from the Google-Weather API'''
    lang = langs.get(lang, 'en')
    url = 'http://www.google.com/ig/api?weather={location}&hl={lang}' \
                                .format(location=location, lang=lang)
    f = ulib.urlopen(url)
    encoding = f.info()['content-type'].split('charset=')[1]
    content = f.read().decode(encoding)
    #print type(content) # "unicode"?
    f.close()

    if parser == 'etree':
        parsed = _parse_weather_lxml(content)
    else:
        parsed = _parse_weather_bss(content)
        
    return parsed

def _parse_weather_lxml(data):
    stored_data = {'forecast_information' : None,
                   'current_conditions' : None,
                   'forecast_conditions' : []}
    
    etree_xml = etree.fromstring(data)
    root = etree_xml.find('weather')
    
    for r_child in root.getchildren():
        tag = r_child.tag
        buf = {}
        if not tag == 'problem_cause': # error?
            for child in r_child:
                buf[child.tag] = child.get('data', '')
            if not tag == 'forecast_conditions':
                stored_data[tag] = buf
            else:
                stored_data[tag].append(buf)
        else: # jep, error!
            stored_data[tag] = r_child.get('data', '')
    
    return stored_data

def _parse_weather_bss(data):
    stored_data = {'forecast_information' : None,
                   'current_conditions' : None,
                   'forecast_conditions' : []}
    
    stonesoup = BeautifulStoneSoup(data)
    
    for r_child in stonesoup.find('weather'):
        tag = r_child.name
        buf = {}
        if not tag == 'problem_cause': # error?
            for child in r_child:
                buf[child.name] = child.get('data', '')
            if not tag == 'forecast_conditions':
                stored_data[tag] = buf
            else: 
                stored_data[tag].append(buf)
        else: # jep, error
            stored_data[tag] = r_child.get('data', '')

    return stored_data

if __name__ == '__main__':
    from pprint import pprint
    
    location = raw_input('Ort/Location: ')
    lang = raw_input('Sprache/Language: ')
    
    parsed_xml = get_weather(location, lang)
    
    if not 'problem_cause' in parsed_xml:
        pprint(parsed_xml)
    else:
        print 'Error:', parsed_xml['problem_cause']
the more they change the more they stay the same
Antworten