疯狂Python讲义Unit4:数字转人民币读法
作者:互联网
#!/usr/bin/python3
'''
num transfer to RMB
借鉴了讲义中4位的数字字符串转换成中文的函数
优化了小数部分和0的处理,仍旧不够完善
'''
# 分离整数和小数部分
def divide(num):
intTemp=int(num)
fractionTemp = round((num-intTemp)*100) # round()函数 用于四舍五入后取整
return(str(intTemp),str(fractionTemp))
HanziList=["零","壹","贰","叁","肆","伍","陆","柒","捌","玖"]
unitList=["十","百","千"]
# 将四位数字转为大写汉字
def four2Hanzi(intTemp):
HanziTemp=""
for i in range(len(intTemp)):
index=int(intTemp[i])
# 依次遍历数字字符串的每一位数字,为4位数字设计,兼容1-3位
if intTemp[i]!="0" and i!=len(intTemp)-1:
# 如果不是最后一位数字,而且数字不是零,则需要添加单位(千、百、十)
HanziTemp+=str(HanziList[index])+unitList[len(intTemp)-2-i]
else:
HanziTemp+=HanziList[index]
return HanziTemp
# 将两位小数转为x角x分
unitList2=["分","角"]
def fraction2Hanzi(fractionTemp):
fractionHanziTemp=""
if len(fractionTemp)==0:
return fractionHanziTemp
elif len(fractionTemp)==1:
if fractionTemp[0]=="0":
return fractionHanziTemp
else:
return HanziList[int(fractionTemp[0])]+"角"
elif len(fractionTemp)==2:
index0=int(fractionTemp[0])
index1=int(fractionTemp[1])
if fractionTemp[0]!="0"and fractionTemp[1]!="0":
return HanziList[index0]+"角"+HanziList[index1]+"分"
elif fractionTemp[0]=="0" and fractionTemp[1]=="0":
return fractionHanziTemp
elif fractionTemp[0]=="0" and fractionTemp[1]!="0":
return HanziList[index1]+"分"
elif fractionTemp[0]!="0" and fractionTemp[1]=="0":
return HanziList[index0] + "角"
else:
pass
return fractionHanziTemp
# 循环比较去重,为重复的0设计
def quchong(strHan):
strResult = ''
strResult += strHan[0]
index = 0
for i in range(1, len(strHan)):
if strHan[i] != strHan[index]:
strResult+=(strHan[i])
index+=1
return strResult
# 数字转人民币,对0的处理仍旧不够完善
def num2Rmb():
num = float(input("请输入一个浮点数(小数点保留2位): "))
intTemp, fractionTemp = divide(num)
str_len = len(intTemp)
if str_len > 12:
print("数值过大,无法转换")
return
# 如果大于8位,包含单位亿
elif str_len > 8:
rmbStr = quchong(four2Hanzi(intTemp[0:-8]))+"亿"+quchong(four2Hanzi(intTemp[-8:-4]))+"万"+quchong(four2Hanzi(intTemp[-4:]))+"元"
elif str_len > 4:
rmbStr = quchong(four2Hanzi(intTemp[0:-4])) + "万" + quchong(four2Hanzi(intTemp[-4:])) + "元"
else:
rmbStr = quchong(four2Hanzi(intTemp[-4:])) + "元"
rmbStr += fraction2Hanzi(fractionTemp)
# 替换一些常用读法
rmbStr = rmbStr.replace('零元','元')
rmbStr = rmbStr.replace('零万','万')
rmbStr = rmbStr.replace('零亿','亿')
rmbStr = rmbStr.replace('亿万','亿')
rmbStr = rmbStr.replace('壹十','十')
return rmbStr
print(num2Rmb())
标签:return,读法,Python,rmbStr,len,HanziList,fractionTemp,intTemp,Unit4 来源: https://blog.csdn.net/Turbo_J/article/details/114608537