数字转汉字

def num2chinese(n):
    chinese = ""
    num_list = list("零一二三四五六七八九十")
    pos1 = list("十百千")
    pos2 = list("万亿兆")
    n_str = str(n)
    if len(n_str)>16:
        print("数字超出范围")
        return -1
    str_list = []
    while len(n_str)>0:
        str_list.insert(0, n_str[-4:])
        n_str = n_str[:-4]
    zero_flag = False
    flag = False
    for cut_num in str_list:
        pos2 = pos2[:(len(str_list)-1)]
        if cut_num=="0000":
            zero_flag = True
            if pos2:
                pos2.pop()
            continue
        if zero_flag:
            chinese += "零"
        if 0<int(cut_num)<=10:
            if cut_num[0]=="0":
                chinese += "零"
            chinese += num_list[int(cut_num)]
            if pos2:
                chinese += pos2.pop()
            continue
        pos_1 = pos1[:(len(cut_num)-1)]
        for num in cut_num:
            if num=="0":
                flag = True
                if pos_1:
                    pos_1.pop()
                continue
            if flag:
                chinese += "零"
            chinese += num_list[int(num)]
            if pos_1:
                chinese += pos_1.pop()
        if pos2:
            chinese += pos2.pop()
    if chinese[0:2]=="一十":
        chinese = chinese[1:]
    return chinese


第二种实现

def num2chinese(n):
    danwei = list(" 十百千万十百千亿十百千兆十百千")
    num_chinese = list("零一二三四五六七八九")
    chinese=""
    n2str = str(n)
    length = len(n2str)
    for i, v in enumerate(n2str):
        chinese += num_chinese[int(v)] + danwei[length-i-1]
    chinese = chinese[1:] if chinese[:2]=="一十" else chinese
    zero_flag = False
    new_chinese = ""
    for x in chinese:
        if x=="零" and not zero_flag:
            zero_flag = True
            new_chinese += "零"
            continue
        if x =="零" and zero_flag:
            continue
        if zero_flag and x in num_chinese:
            zero_flag = False
        if zero_flag and x in ("十", "百", "千"):
            continue
        if zero_flag and x in ("兆","亿","万"):
            new_chinese = new_chinese[:-1]
            zero_flag = False
        new_chinese += x
    new_chinese = new_chinese.replace("亿万","亿")
    new_chinese = new_chinese.replace("兆亿","兆")
    new_chinese = new_chinese.strip().strip("零")
    return new_chinese


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值