feat:retorna codigo do ibge do nome do municipio e da uf by CarduCaldeira · Pull Request #411 · brazilian-utils/python

import pandas as pd
import unicodedata
import json


def _transform_text(municipality_name: str): # type: (str) -> str
   """ 
   Normalize municipality name and returns the normalized string.

   Args:
        municipality_name (str): The name of the municipality.
        
    Returns:
        str: The normalized string

    Example:
        >>> _transform_text("São Paulo")
        "sao paulo"
        >>> _transform_text("Goiânia")
        "goiania"
        >>> _transform_text("Conceição do Coité")
        "'conceicao do coite'
    """

   normalized_string = (unicodedata.normalize('NFKD', municipality_name)
                        .encode('ascii','ignore').decode('ascii'))
   case_fold_string = normalized_string.casefold()

   return case_fold_string

def create_json():
    """
    Load the municipal code from an .xls file and 
    structure it in a json file
    """
    
    file_path = './RELATORIO_DTB_BRASIL_MUNICIPIO.xls'
    df = pd.read_excel(file_path)
    
    #select only 'Nome_UF','Nome_Município','Código Município Completo' columns
    df_only =  df[['Nome_UF','Nome_Município','Código Município Completo']]
    df_only.loc[:, 'Nome_UF'] = df_only['Nome_UF'].apply(_transform_text)
    df_only.loc[:, 'Nome_Município'] = (df_only['Nome_Município']
                                        .apply(_transform_text))
    
    #Change the name of the municipality to its acronym
    uf_codes = {'acre': 'AC', 'alagoas': 'AL', 
     'amapa': 'AP', 'amazonas': 'AM', 
     'bahia': 'BA', 'ceara': 'CE', 
     'distrito federal': 'DF', 'espirito santo': 'ES', 
     'goias': 'GO', 'maranhao': 'MA', 'mato grosso': 'MT', 
     'mato grosso do sul': 'MS', 'minas gerais': 'MG', 
     'para': 'PA', 'paraiba': 'PB', 'parana': 'PR', 
     'pernambuco': 'PE', 'piaui': 'PI', 
     'rio de janeiro': 'RJ', 'rio grande do norte': 'RN', 
     'rio grande do sul': 'RS', 'rondonia': 'RO', 
     'roraima': 'RR', 'santa catarina': 'SC', 
     'sao paulo': 'SP', 'sergipe': 'SE', 'tocantins': 'TO'}
    
    df_only.loc[:,'Nome_UF'] = df_only['Nome_UF'].map(uf_codes)

    #create ./cities_code.json' file
    result = {}

    for _, row in df_only.iterrows():
        
        state = row['Nome_UF']
        municipality = row['Nome_Município']
        code = row['Código Município Completo']
        
        if state not in result:
            result[state] = {}
        result[state][municipality] = code

    with open('./cities_code.json', 'w') as json_file:
        json.dump(result, json_file, indent=4)