數字轉中文 python

anthea_luo發表於2020-12-04

 

一億以內阿拉伯數字轉中文  第一想法 只有用字典對映轉換,四位四位處理。好多規則,好多if -else。

冷靜下來再想想   可以不用四位四位處理:一次性轉換後再逆序在指定位置上插入“量詞”後再逆序回來。相對少一點if-else, 稍優雅一點點的版本如下:

 

 

# encoding: utf-8


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


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


def auth(num):
    if not isinstance(num, int):
        print("error input, should be integer")
        return False
    if abs(num) > 1e8:
        print("error input, abs value should be less than 1e8")
        return False
    return True
    

def num2chinese(num):
    if not auth(num):
        return ""
    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__':
   print(num2chinese(67090))

 

 

 

相關文章