Advertisement
mixster

mixster

Oct 19th, 2010
398
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.28 KB | None | 0 0
  1. #!/usr/bin/env python
  2.  
  3. import xml.parsers.expat
  4. import urllib
  5.  
  6. url = 'http://api.erepublik.com/v2/feeds/countries'
  7.  
  8. f = urllib.urlopen(url)
  9.  
  10. s = ''
  11. for line in f:
  12.   s += line
  13.  
  14. f.close()
  15.  
  16. population = ''
  17. checkPop  = False
  18. checkName = False
  19. inRegions = False
  20.  
  21. countries = []
  22.  
  23. p = xml.parsers.expat.ParserCreate()
  24. def start_element(name, attrs):
  25.   global checkPop, checkName, inRegions
  26.   if name == 'citizen-count':
  27.     checkPop = True
  28.   elif not inRegions and name == 'name':
  29.     checkName = True
  30.   elif name == 'regions':
  31.     inRegions = True
  32.  
  33. def end_element(name):
  34.   global inRegions
  35.   if name == 'regions':
  36.     inRegions = False
  37.  
  38. def char_data(data):
  39.   global checkPop, checkName, population, countries
  40.  
  41.   if checkPop:
  42.     population = data
  43.     checkPop = False
  44.   elif checkName:
  45.     countries.append((data, int(population)))
  46.     checkName = False
  47.  
  48. p = xml.parsers.expat.ParserCreate()
  49.  
  50. p.StartElementHandler = start_element
  51. p.EndElementHandler = end_element
  52. p.CharacterDataHandler = char_data
  53.  
  54. p.Parse(s)
  55.  
  56. m = len(countries)
  57. for a in range(1, m):
  58.   t = countries[a]
  59.   b = a - 1
  60.   while (b >= 0 and t[1] > countries[b][1]):
  61.     countries[b + 1] = countries[b]
  62.     b -= 1
  63.   countries[b + 1] = t
  64.  
  65. for c in countries:
  66.   print c[0] + ': ', c[1]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement