Discuss / Python / 作业

作业

Topic source

蓝e随风

#1 Created at ... [Delete] [Delete and Lock User]
from urllib import request
from xml.parsers.expat import ParserCreate

def get_xml(url):
    with request.urlopen(url) as f:
        data = f.read()
        return data.decode('utf-8')


class weatherHandler(object):
    def __init__(self):
        self.result = {}
        self.L = []

    def start_element(self, name, attrs):
        # print('name:', name, 'attrs:', str(attrs))
        if 'location' in name:
            self.result['city'] = attrs['city']
        if 'date' in str(attrs) and 'day' in str(attrs) and 'high' in str(attrs) and 'low' in str(attrs) and 'weather' in str(attrs):
            forecase = {
                'date': attrs['date'],
                'day':  attrs['day'],
                'high': attrs['high'],
                'low': attrs['low'],
                'weather': attrs['text']
            }
            self.L.append(forecase)

    def end_element(self, name):
        if name == 'query':
            self.result['forecase'] = self.L

    def char_data(self, text):
        pass

def paseXml(xml_str):
    handler = weatherHandler()
    parser = ParserCreate()
    parser.StartElementHandler = handler.start_element
    parser.EndElementHandler = handler.end_element
    parser.CharacterDataHandler = handler.char_data
    parser.Parse(xml_str)
    return handler.result

xml_str = get_xml('https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20weather.forecast%20where%20woeid%20%3D%202151330&format=xml')
result = paseXml(xml_str)

蓝e随风

#2 Created at ... [Delete] [Delete and Lock User]

if 'date' in str(attrs) and 'day' in str(attrs) and 'high' in str(attrs) and 'low' in str(attrs) and 'weather' in str(attrs): 改为: if reduce(lambda x, y: x & y, map(lambda x: x in str(attrs), ['date', 'day', 'high', 'low', 'weather'])):


  • 1

Reply