defnum2cn(num): num = int(num) if num == 0: return'零' elif num == 1: return'一' elif num == 2: return'二' elif num == 3: return'三' elif num == 4: return'四' elif num == 5: return'五' elif num == 6: return'六' elif num == 7: return'七' elif num == 8: return'八' elif num == 9: return'九' else: print('input type error') exit(1)
defone2thousand(x): first_no_zero = False # 保存结果 result = [] x = str(x) # 填充到千位 x = x.rjust(4,"0") len_x = len(x) sub_suffix = suffix[:len_x] sub_suffix.reverse() for index, num in enumerate(x): if num == '0': if first_no_zero == True: # 在遇到首个非零数字前,遇到的0都是填充的 result.append(num2cn(num)) else: result.append(num2cn(num)) result.append(sub_suffix[index]) first_no_zero = True if len(result) == 0: # 输入为0的特殊情况 return'零' out = "".join(result) # 处理中间的零,将多个“零”,变为一个“零”,如一千零零一 --> 一千零一 out = re.sub('零+','零',out) # 处理末尾的零,,如一千一百零 --> 一千一百 out = re.sub('零+$','',out) return out
for i in range(10): inp = str(random.randint(0,10000)) print('数字:%s \t中文读法:%s'%(inp,one2thousand(inp)))
# # 2. 个到千的规则定义好了,接着将一个数字拆分为许多个到千来处理
suffix2 = ['亿','万','']
defzh_cnNum(x): result = [] x = str(x) len_x = len(x) # 将x填充到千亿位 x = x.rjust(len(suffix),"0") sub_suffix = suffix[:4] # 每次取出4位进行千位读法,并加上单位,如'亿','万',... for i in range(3): sub_x = x[i*4:i*4+4] out = one2thousand(sub_x) if out != '零': result.append(out) result.append(suffix2[i]) if len(result) == 0: # 输入为0的特殊情况 return'零' return"".join(result)
for i in range(10): inp = str(random.randint(0,100000000001)) print('数字:%s \t中文读法:%s'%(inp,zh_cnNum(inp)))