-
-
Save barraponto/21c705006635a1a72407 to your computer and use it in GitHub Desktop.
Pythonic sum of 2014 World Cup spendings
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Muito bom