Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python
- import xml.parsers.expat
- import urllib
- url = 'http://api.erepublik.com/v2/feeds/countries'
- class Countries(object):
- def __init__(self):
- self.countries = []
- def newElement(self, name, attrs):
- if name == 'country':
- self.countries.append(Country())
- else:
- if len(self.countries) > 0:
- self.countries[-1].newElement(name, attrs)
- def endElement(self, name):
- if len(self.countries) > 0:
- self.countries[-1].endElement(name)
- def newData(self, data):
- if len(self.countries) > 0:
- self.countries[-1].newData(data)
- class Country(object):
- def __init__(self):
- self.regions = []
- self.mode, self.name, self.id, self.currency = '', '', '', ''
- self.population = 0
- def newElement(self, name, attrs):
- if self.mode == 'regions':
- if name == 'region':
- self.regions.append(Country())
- else:
- if len(self.regions) > 0:
- self.regions[-1].newElement(name, attrs)
- else:
- self.mode = name
- def endElement(self, name):
- self.mode = ''
- if len(self.regions) > 0:
- self.regions[-1].endElement(name)
- def newData(self, data):
- if self.mode == 'name':
- self.name = data
- elif self.mode == 'id':
- self.id = data
- elif self.mode == 'currency':
- self.currency = data
- elif self.mode == 'citizen-count':
- self.population = int(data)
- elif len(self.regions) > 0:
- self.regions[-1].newData(data)
- class Region(object):
- def __init__(self):
- self.mode, self.name, self.id = '', '', ''
- def newElement(self, name, attrs):
- self.mode = name
- def endElement(self, name):
- self.mode = ''
- def newData(self, data):
- if self.mode == 'name':
- self.name = data
- elif self.mode == 'id':
- self.id = data
- f = urllib.urlopen(url)
- s = ''
- for line in f:
- s += line
- f.close()
- countries = Countries()
- p = xml.parsers.expat.ParserCreate()
- p.StartElementHandler = countries.newElement
- p.EndElementHandler = countries.endElement
- p.CharacterDataHandler = countries.newData
- p.Parse(s)
- m = len(countries.countries)
- for a in range(1, m):
- t = countries.countries[a]
- b = a - 1
- while (b >= 0 and t.population > countries.countries[b].population):
- countries.countries[b + 1] = countries.countries[b]
- b -= 1
- countries.countries[b + 1] = t
- for c in countries.countries:
- print c.name + ' (' + c.id + '): ', c.population, ' - ' + c.currency
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement