数字转中文 python

 

一亿以内阿拉伯数字转中文  第一想法 只有用字典映射转换,四位四位处理。好多规则,好多if -else。

后来再想想   可以不用四位四位处理:一次性转换后再逆序在指定位置上插入中间连接的“量词”后再逆序回来。相对少一点if-else, 稍优雅一点点的版本如下:

 

 

# encoding: utf-8


num_dict= \
{"0":"零",
 "1":"一",
 "2":"二",
 "3":"三",
 "4":"四",
 "5":"五",
 "6":"六",
 "7":"七",
 "8":"八",
 "9":"九",
 "-":"负"}


concat_mid_list = ["", "十", "百", "千", "万"]


def auth(input_num):
    if not input_num.isdigit():
        if not (len(input_num) > 1 and input_num[0] == "-" and input_num[1:].isdigit()):
            print("error input, should be integer")
            return False
    if abs(int(input_num)) > 1e8:
        print("error input, abs value should be less than 1e8")
        return False
    return True
    

def num2chinese(num):
    temp_chinese = derect_translate(num)
    # print("temp_chinese is ", temp_chinese)
    updated_chinese = update(temp_chinese)
    if num >= 0:
        return updated_chinese
    return num_dict[str(num)[0]] + updated_chinese

    
def derect_translate(num): 
    return [num_dict[x] for x in str(abs(num))]


def update(temp_chinese):
    tmp_inf = []
    for ix, x in enumerate(temp_chinese[::-1]):
        if x == "零":
            # 当前位为0时 特殊处理重复零(上一个为零)问题
            if tmp_inf and (tmp_inf[-1] == "零" or tmp_inf[-1] == "万"):
                pass
            elif tmp_inf or len(temp_chinese) == 1:
                tmp_inf.append(x)
        else:
            tmp_inf.append(x + concat_mid_list[ix % 4])
        # 特殊处理 万这个单位上的字符
        if ix == 3 and len(temp_chinese) > 4:
            tmp_inf.append("万")
    # print("tmp_inf is ", tmp_inf)
    tmp_inf.reverse()
    return "".join(tmp_inf)
  

if __name__ == "__main__":
    while True:
        input_num = input("please in put a number or q to exit: ")
        if input_num == "q":
            break
        if not auth(input_num):
            continue
        print(num2chinese(int(input_num)))

 

 

 

你可能感兴趣的:(python)