StringAux.py 2.49 KB
#!/usr/bin/python
# -*- coding: utf-8 -*-

from unicodedata import normalize

ext = {1:"um", 2:"dois", 3:"três", 4:"quatro", 5:"cinco", 6:"seis", 7:"sete", 8:"oito", 9:"nove", 0:"zero"}

def extenso(n):
    strn = str(n)
    sizen = len(strn)
    tokens = []
    for i in range (0, sizen):
        x = int(strn[i])
        tokens.append(ext[x])
    return ' '.join(tokens)

"""
def extenso(n):
    strn = str(n)
    sizen = len(strn)
    tokens = []
    for i in range (0, sizen):
        tokens.append(strn[i])
    return ' '.join(tokens)
"""    

def remover_acentos(txt):

    """ Devolve cópia de uma str substituindo os caracteres 
        acentuados pelos seus equivalentes não acentuados.
    
    ATENÇÃO: carateres gráficos não ASCII e não alfa-numéricos,
    tais como bullets, travessões, aspas assimétricas, etc. 
    são simplesmente removidos!
    
    >>> remover_acentos('[ACENTUAÇÃO] ç: áàãâä! éèêë? íìĩîï, óòõôö; úùũûü.')
    '[ACENTUACAO] c: aaaaa! eeee? iiiii, ooooo; uuuuu.'
    
    """
    try:
        return normalize('NFKD', txt.decode('utf-8')).encode('ASCII','ignore')
    except:
        return normalize('NFKD', txt.decode('iso-8859-1')).encode('ASCII','ignore')


def roman_to_int(input):
    if not isinstance(input, type("")):
        raise TypeError, "expected string, got %s" % type(input)
    input = input.upper( )
    nums = {'M':1000,
            'D':500,
            'C':100,
            'L':50,
            'X':10,
            'V':5,
            'I':1}
    sum = 0
    for i in range(len(input)):
        try:
            value = nums[input[i]]
            if i+1 < len(input) and nums[input[i+1]] > value:
                sum -= value
            else: sum += value
        except KeyError:
            raise ValueError, 'input is not a valid Roman numeral: %s' % input
        
    if int_to_roman(sum) == input: return sum
    else:        raise ValueError, 'input is not a valid Roman numeral: %s' % input

def int_to_roman(input):
    if not isinstance(input, type(1)):
        raise TypeError, "expected integer, got %s" % type(input)
    if not 0 < input < 4000:
        raise ValueError, "Argument must be between 1 and 3999"
    ints = (1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1)
    nums = ('M', 'CM', 'D', 'CD','C', 'XC','L','XL','X','IX','V','IV','I')
    result = []

    for i in range(len(ints)):
        count = int(input / ints[i])
        result.append(nums[i] * count)
        input -= ints[i] * count
    return ''.join(result)