今天把功能补全了,可以实现完全的转换功能,包括小数部分。
主要就是增加了用float
函数判断输入是否合法,用preTreatment
函数将数字分为整数和小数部分,然后用convert
函数来对两部分分别进行处理。
import re
digits = list('0123456789')
accDigits = list('零壹贰叁肆伍陆柒捌玖')
units = ['', '拾', '佰', '仟']
sep = list('分角元万亿兆')
acc_conv_dict = dict(zip(digits, accDigits))
def preTreatment(num):
num = '{:.2f}'.format(float(num))
partition = num.partition('.')
iPart, fPart = partition[0], partition[2]
return iPart, fPart
def convert(num):
iPart, fPart = preTreatment(num)
blocks = four_digits_block(iPart)
iPartStr, fPartStr = '', ''
for blockIndex in range(len(blocks)):
block = blocks[blockIndex]
for index in range(4):
if not (blockIndex == 0 and index == 2 and block[index] == '1'):
iPartStr += acc_conv_dict[block[index]]
if block[index] != '0':
iPartStr += units[3 - index]
iPartStr = iPartStr.strip('零')
iPartStr += sep[len(blocks) - blockIndex + 1]
iPartStr = re.sub('零+', '零', iPartStr)
for index in range(len(fPart)):
fPartStr += acc_conv_dict[fPart[index]]
if fPart[index] != '0':
fPartStr += sep[1 - index]
fPartStr = fPartStr.strip('零')
if fPartStr == '':
result = iPartStr + '整'
else:
result = iPartStr + fPartStr
return result
def four_digits_block(iPart):
fill_counter = 4 - (len(iPart) % 4) if len(iPart) % 4 != 0 else 0
zero_fill = iPart.zfill(fill_counter + len(iPart))
blocks = [zero_fill[i * 4:(i + 1) * 4] for i in range(len(zero_fill) // 4)]
return blocks
while True:
num = input("请输入数字:")
if num == '':
print('欢迎您再次使用,再见!')
break
try:
float(num)
except:
print('输入数字不合法!')
pass
result = convert(num)
print(result)
网友评论