代码改变世界

数字转中文大写=> 1234=> 一千二百三十四

2018-12-04 11:16  夏洛克·福尔摩斯  阅读(1837)  评论(0编辑  收藏  举报
# -*- coding: utf-8 -*-
# 最大值:九兆九千九百九十九亿九千九百九十九万九千九百九十九
import re
p = ['', '', '', '', '', '', '', '', '亿', '', '', '', '']
s = ['', '', '', '', '', '', '', '', '', '']
def num2zh(num_str):
    res = ''
    t = list(str(num_str))
    t.reverse()
    for idx, tmp in enumerate(t):
        if int(tmp) == 0:
            res = '' + res
            if idx % 4 == 0 and idx > 0:
                res = p[idx] + res
            continue
        res = s[int(tmp)] + p[idx] + res
    # 零+ -> 零
    out = re.sub(r'(\xe9\x9b\xb6)+', '', res)
    # 零万 -> 万
    out = re.sub(r'\xe9\x9b\xb6\xe4\xb8\x87', '', out)
    # 一十 -> 十
    out = re.sub(r'(^\xe4\xb8\x80\xe5\x8d\x81)', '', out)
    # 零亿 -> 亿 
    out = re.sub(r'\xe9\x9b\xb6\xe4\xba\xbf', '亿', out)
    # 亿万 -> 亿 
    out = re.sub(r'\xe4\xba\xbf\xe4\xb8\x87', '亿', out)
    # 兆亿 -> 兆 
    out = re.sub(r'\xe5\x85\x86\xe4\xba\xbf', '', out)
    # 去掉最后的零
    out = re.sub(r'(\xe9\x9b\xb6)$', '', out)
    return out
print(num2zh(1234))