本文實例為大家分享了python實現人民幣大寫轉換的具體代碼,供大家參考,具體內容如下
#!/usr/bin/python# -*- coding:utf-8 -*-# ********* 轉換方法介紹 *********# 將需要轉換的數字從右向左,每4位分成一個section,如:24530467103,將該數字拆分后,得到:# 245 3046 7103 (245億3046萬7103)# 對拆分后的數字先按照section進行數字到漢字的轉換,然后添加數值單位,如:仟,佰,拾,處理結束后可以得到轉換后的序列。# 對section處理結束后,再對每個section進行單位的追加。如:兆、億、萬。# 這里需要注意一些特殊情況,如:section中連續出現0,最后一個數字為0等。DEBUG = Trueupper = ["零", "壹", "貳", "叁", "肆", "伍", "陸", "柒", "捌", "玖"]decimal_unit = ["角", "分", "厘", "毫"]section_unit = ["萬", "億", "兆"]count_unit = ["拾", "佰", "仟"]def dbg_print(s): if DEBUG: print(s)def split_num(num): num_list = [] if (len(num) <= 4): num_list.append(num) return num_list while (len(num)): if (len(num) <= 4): num_list.append(num) num_list.reverse() return num_list sec = num[-4:] num_list.append(sec) num = num[:-4]# 處理小數部分,只支持4位,多于4位,四舍五入。def convert_dec(num): result = "" count = 0 dbg_print(num) for i in num: n = int(i) if (0 != n): result += upper[n] result += decimal_unit[count] count += 1 dbg_print(result) return result# 處理整數部分def convert_int(num): section_list = split_num(num) dbg_print(num) dbg_print(section_list) result = "" sec_index = len(section_list) - 2 for item in section_list: index = len(item) - 2 # 統計連續出現的數字0的個數。 flag = 0 # 計算遍歷過的item中的字符數。 count = 0 # 對每個section進行處理,得到數字對應的漢字。 for i in item: n = int(i) if (0 == n): flag += 1 else: flag = 0 # 用來區分section的最后一位為0的情況 if (count != len(item)-1): # 該位置的數字為0,并且它的下一個數字非0。 if ((flag >= 1) and ('0' != item[count+1])): result += upper[n] else (0 != n): result += upper[n] else: # section的最后一個數字非0的情況。 if (0 != n): result += upper[n] # 最后一個數字以及數字為0時,都不需要添加單位。 if ((index >= 0) and (0 != n)): result += count_unit[index] index += 1 count += 1 從第1個section開始,如果section中的數字不全為0,其后就需要添加section對應的單位。 if (sec_index >= 0 and flag != count): result += section_unit[sec_index] dbg_print(result) sec_index -= 1 result = result.replace("壹拾", "拾") result += "元" return result# 轉換函數def convert(num): result = "" num = round(float(num), 4) integer,decimal = str(num).split('.') result_int = convert_int(integer) result_dec = convert_dec(decimal) if (len(result_dec) == 0): result = result_int += "整" else: result = result_int + result_dec return result
新聞熱點
疑難解答