[随便写写] 数字转汉字翻译器

d = ['', '十', '百', '千']
ddd = ['', '万', '亿', '兆']
dd = {
    '0': '零',
    '1': '一',
    '2': '二',
    '3': '三',
    '4': '四',
    '5': '五',
    '6': '六',
    '7': '七',
    '8': '八',
    '9': '九',
}


def get_cell(inputs):
    if len(inputs) <= 4:
        length = len(inputs)
        output = []

        for index in range(length):
            num = inputs[index]
            num_chinese = dd[num]
            danwei = d[length - index - 1]

            if int(num) == 0 and index != length - 1:
                danwei = ''

            if int(num) == 0 and index == length - 1:
                num_chinese = ''

            output.append(num_chinese)
            output.append(danwei)

    output = "".join(output)
    while output.find('零零') != -1:
        output = output.replace('零零', '零')
    return output

def get_xiaoshu(inputs):
    return "".join([dd[num] for num in inputs])

def g(inputs):
    output = []
    cells = []

    if inputs[0] == '0':
        print('Wrong Format')
        raise BaseException

    is_xiaoshu = inputs.find('.')
    if is_xiaoshu != -1:
        xiaoshu = inputs[is_xiaoshu+1:]
        inputs = inputs[:is_xiaoshu]


    # 每4个作为一个单位进行处理
    while len(inputs) > 4:
        cur = inputs[-4:]
        cells.append(cur)
        inputs = inputs[:-4]

    cells.append(inputs)

    for index in range(len(cells)):
        output.append(get_cell(cells[index])+ddd[index])


    result = "".join(output[::-1])

    # 去除最后的零
    if result[-1] == '零':
        result = result[:-1]

    if is_xiaoshu != -1:
        result = result + '点' + get_xiaoshu(xiaoshu)

    return result

print(g('43000223401.10400'))

结果 : 四百三十亿零二十二万三千四百零一点一零四零零

你可能感兴趣的:(python)