Created
September 8, 2019 15:54
-
-
Save tflores/f111d80312130ab07bad7edd35da0882 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
""" | |
Programa para baixar dados do TSE e gerar estatísticas eleitorais usando Python 3.7 | |
""" | |
# Importacão de bibliotecas necessárias | |
import pandas as pd | |
import os | |
import fnmatch | |
from zipfile import ZipFile | |
from urllib.request import urlopen | |
urldados = "http://agencia.tse.jus.br/estatistica/sead/odsele/detalhe_votacao_munzona/detalhe_votacao_munzona_2018.zip" | |
dirdados = "./dados" | |
tmpdir = "./temp" | |
# Obtem arquivo zip e salva-o no diretório temporário | |
zipresp = urlopen(urldados) | |
tempzip = open(f"{tmpdir}/tempfile.zip", "wb") | |
tempzip.write(zipresp.read()) | |
tempzip.close() | |
# Extrai arquivos do zip para diretório de dados | |
zf = ZipFile(f"{tmpdir}/tempfile.zip") | |
zf.extractall(path=dirdados) | |
zf.close() | |
# Prepara DataFrame para receber os dados | |
tabela = pd.DataFrame( | |
columns=['DT_GERACAO', 'HH_GERACAO', 'ANO_ELEICAO', 'CD_TIPO_ELEICAO', 'NM_TIPO_ELEICAO', 'NR_TURNO', 'CD_ELEICAO', | |
'DS_ELEICAO', 'DT_ELEICAO', 'TP_ABRANGENCIA', 'SG_UF', 'SG_UE', 'NM_UE', 'CD_MUNICIPIO', 'NM_MUNICIPIO', | |
'NR_ZONA', 'CD_CARGO', 'DS_CARGO', 'QT_APTOS', 'QT_SECOES', 'QT_SECOES_AGREGADAS', 'QT_APTOS_TOT', | |
'QT_SECOES_TOT', 'QT_COMPARECIMENTO', 'QT_ABSTENCOES', 'ST_VOTO_EM_TRANSITO', 'QT_VOTOS_NOMINAIS', | |
'QT_VOTOS_BRANCOS', 'QT_VOTOS_NULOS', 'QT_VOTOS_LEGENDA', 'QT_VOTOS_PENDENTES', 'QT_VOTOS_ANULADOS', | |
'HH_ULTIMA_TOTALIZACAO', 'DT_ULTIMA_TOTALIZACAO']) | |
# Processa os arquivos | |
lista_arquivos = os.listdir(dirdados) | |
pattern = "*.csv" | |
for entry in lista_arquivos: | |
if fnmatch.fnmatch(entry, pattern): | |
print(entry) | |
tabela = tabela.append(pd.read_csv(f'{dirdados}/{entry}', sep=';', encoding='latin_1'), ignore_index=True) | |
print(tabela.shape) | |
print(tabela.head()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment