个人认为WeatherSaxHandler中应该是尽可能多地采集信息,parse_weather中是筛选目前可用信息,并通过一定格式返回到更上层,这样我们就能以最小的改动跟随上层的需求变动。
WeatherSaxHandler
parse_weather
class WeatherSaxHandler(object): info = {} cnt = {} def _attrs_filter(self, attrs): for x in attrs: t = attrs[x] attrs[x] = int(t) if t.isdigit() else t return attrs def start_element(self, name, attrs): if ':' in name: attrs = self._attrs_filter(attrs) key = name[name.index(':')+1::] if key not in self.info: self.info[key] = attrs else: if key not in self.cnt: self.cnt[key] = 1 else: self.cnt[key] += 1 self.info[key+'(%d)'% self.cnt[key]] = attrs def end_element(self, name): pass def char_data(self, text): pass def parse_weather(xml): weatherHandler = WeatherSaxHandler() weatherParser = ParserCreate() weatherParser.StartElementHandler = weatherHandler.start_element weatherParser.EndElementHandler = weatherHandler.end_element weatherParser.CharacterDataHandler = weatherHandler.char_data weatherParser.Parse(xml) info = weatherHandler.info return { 'city':info['location']['city'], 'country':info['location']['country'], 'today':info['forecast'], 'tomorrow':info['forecast(1)']} info = parse_weather(data)
真是这样么?
Sign in to make a reply
久疤_796
个人认为
WeatherSaxHandler
中应该是尽可能多地采集信息,parse_weather
中是筛选目前可用信息,并通过一定格式返回到更上层,这样我们就能以最小的改动跟随上层的需求变动。