Skip to content

Instantly share code, notes, and snippets.

@barraponto
Forked from fmasanori/Copa2014.py
Last active May 20, 2016 02:32
Show Gist options
  • Save barraponto/21c705006635a1a72407 to your computer and use it in GitHub Desktop.
Save barraponto/21c705006635a1a72407 to your computer and use it in GitHub Desktop.
Pythonic sum of 2014 World Cup spendings
# coding: utf-8
from urllib.request import urlopen
from xml.etree import ElementTree
class Budget(object):
'''2014 World Cup budget parser.'''
def __init__(self, data_url):
'''Parses XML from data_url.'''
with urlopen(data_url) as response:
self.tree = ElementTree.parse(response)
def __iter__(self):
'''Iterate over spending lines from the budget.'''
xpath = './/copa:empreendimento'
namespaces = {'copa': 'http://www.portaltransparencia.gov.br/copa2014'}
for element in self.tree.iterfind(xpath, namespaces=namespaces):
yield Spending(element)
class Spending(object):
'''2014 World Cup spending line.'''
def __init__(self, element):
self.element = element
@property
def value(self):
'''Get the spending value, if any.'''
value = self.element.find('./valorTotalPrevisto')
return None if value is None else float(value.text)
@property
def started(self):
'''Check whether spending has started.'''
return self.element.find('./andamento/id').text != '1'
if __name__ == '__main__':
# setup locale for pretty printing the spending.
import locale
locale.setlocale(locale.LC_ALL, 'pt_BR.UTF-8')
budget = Budget('http://www.portaltransparencia.gov.br/copa2014/api/rest/empreendimento')
total_spending = sum(spending.value for spending in budget
if (spending.value is not None) and spending.started)
print(locale.currency(total_spending, grouping=True))
@zrhans
Copy link

zrhans commented Jul 9, 2015

Muito bom

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment