Discuss / Python / 写一个开始方法就行了

写一个开始方法就行了

Topic source

抑郁胖子

#1 Created at ... [Delete] [Delete and Lock User]
d, a = {}, []
class WeatherSaxHandler(object):

    def start_element(self, name, attrs):
        if name.endswith('location'):
            d['city'] = attrs['city']
            d['country'] = attrs['country']
        if name.endswith('forecast') and len(a) < 2:
            a.append({'text': attrs['text'],'low': int(attrs['low']),'high': int(attrs['high'])})
            if len(a) == 2:
                d['today'] = a[0]
                d['tomorrow'] = a[1]

def parse_weather(xml):
    handler = WeatherSaxHandler()
    parser = ParserCreate()
    parser.StartElementHandler = handler.start_element
    parser.Parse(data)
    return d

抑郁胖子

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

这样好像好点

class WeatherSaxHandler(object):
    def start_element(self, name, attrs):
        if name.endswith('location'):
            d['city'] = attrs['city']
            d['country'] = attrs['country']
        if name.endswith('forecast'):
            if not 'today' in d:
                d['today'] = {'text': attrs['text'],'low': attrs['low'],'high': attrs['high']}
            elif not 'tomorrow' in d:
                d['tomorrow'] = {'text': attrs['text'],'low': attrs['low'],'high': attrs['high']}

  • 1

Reply