人民币数字大写转换

要求

  1. 中文大写金额数字应用壹、贰、叁、肆、伍、陆、柒、捌、玖、拾、佰、仟、万、亿、元、角、分、零、整(正)等字样。
  2. 中文大写金额数字到"元"为止的,在"元"之后,应写"整"(或"正")字,在"角"之后,可以不写"整"(或"正")字。
  3. 中文大写金额数字前应标明"人民币"字样,大写金额数字有"分"的,“分"后面不写"整”(或"正")字。
  4. 大写金额数字应紧接"人民币"字样填写,不得留有空白。
  5. 阿拉伯数字小写金额数字中有"0"时,中文大写应按照汉语语言规律、金额数字构成和防止涂改的要求进行书写。

举例如下

  1. 阿拉伯数字中间有"0"时,中文大写要写"零"字,如¥1409.50,应写成:人民币壹仟肆佰零玖元伍角。
  2. 阿拉伯数字中间连续有几个"0"时,中文大写金额中间只写一个"零"字,如¥6007.14,应写成:人民币陆仟零柒元壹角肆分。
  3. 阿拉伯金额数字万位和元位是"0",或者数字中间连续有几个"0",万位、元位也是"0",但千位、角位不是"0"时,中文大写金额中只写一个零字,也可以不写"零"字。如¥1680.32,应写成:人民币壹仟陆佰捌拾元叁角贰分,又如¥107000.53,应写成:人民币壹拾万零柒仟元伍角叁分。
  4. 阿拉伯金额数字角位是"0",而分位不是"0"时,中文大写金额"元"后面应写"零"字。如¥16409.02,应写成人民币:壹万陆仟肆佰零玖元零贰分;又如¥325.04,应写成人民币叁佰贰拾伍元零肆分。

过程

反向等长切分字符串

inte_group = [integral[::-1][i:i+4][::-1] for i in range(0, len(integral), 4)][::-1]

参数极端值

存储单位的list中,有个单位为无,为了统一处理,可以使用空单位占位子。

    unit_group_map = ('仟', '佰', '拾', '')

处理思路

从低位到高位分节处理

代码

估计还是有些瑕疵。

import sys
import re

def convert2Accounting(src):
    res_prefix = "人民币"
    res = ""
    num_map = "零壹贰叁肆伍陆柒捌玖"
    unit_map = ('万亿亿','亿亿','万亿','亿', '万', '元')

    def convert_groups(group):
        res_group = ""
        unit_group_map = ('仟', '佰', '拾', '')
        for i in range(-1, -len(group)-1, -1):
            res_group = ((num_map[int(group[i])] + unit_group_map[i]) 
                        if (group[i] != '0') else '零') + res_group
        return res_group.rstrip('零')

    def convert_integral(integral):
        res_inte = ""
        inte_group = [integral[::-1][i:i+4][::-1]
                            for i in range(0, len(integral), 4)][::-1]
        for i in range(-1, -len(inte_group)-1, -1):
            res_inte = (((convert_groups(inte_group[i]) + unit_map[i]) 
                            if convert_groups(inte_group[i]) != '' else '') 
                            + res_inte)
        return res_inte


    if not re.match(r'¥\d{0,' + str(len(unit_map)*4) + r'}(\.\d{1,2})?$', src):
        return "Format Error!"

    src = src[1:]
    if src[0] == '0':
        src = src.lstrip('0')

    if src.count('.') == 0:
        integral = src
        res = convert_integral(integral)
    elif src.count('.') == 1:
        integral, decimal = src.split('.')
        res = convert_integral(integral)
        unit_decimal_map = "角分"
        for i in range(0, len(decimal)):
            res += ((num_map[int(decimal[i])] + unit_decimal_map[i])
                    if (decimal[i] != '0') else '零')
    else:
        res = "The count of '.' should be 0 or 1"


    res = res_prefix + res 
    while res.count("零零"):
        res = res.replace("零零", "零")
    if res.endswith('零'):
        res = res[:-1]
    if res.endswith('元'):
        res += '整'
    for unit in unit_map:
        if res.count('零'+unit):
            res = res.replace('零'+unit, unit)

    return res

if __name__ == "__main__":
    print(convert2Accounting(sys.argv[1]))

猜你喜欢

转载自blog.csdn.net/Tifa_Best/article/details/88902615