面试时发现的一道笔试题(金额读写操作)
IDE:pycharm
python版本:python3.8
dic_num = [{'1': '壹', '2': '贰', '3': '叁', '4': '肆', '5': '伍', '6': '陆', '7': '柒', '8': '捌', '9': '玖', '0': '零'}, '拾',
'佰', '仟', '万']
figure = ['元', '万', '亿', '兆']
# 小数部分字符串
def data_num_split(input_num):
'''
整个金额分割函数
:return: 小数部分和整数部分
'''
j = 0
if '.' not in input_num: # input_num 等于整数
integer = input_num
decimals = ''
else: # input_num 等于小数
for i in input_num.split("."): # 以小数点进行切割转列表
if j == 0:
integer = i # 整数
j += 1
else:
decimals = i # 小数点后数值
return integer[::-1], decimals
# 对数值进行分割
def groupful_num():
num_group1 = []
num_group2 = []
count = 0
while True:
for i in integer: # 循环输入的数值
count += 1
num_group1.append(i) # 将循环后的值,依次添加到列表汇总
if count % 4 == 0: # 计算取余4等于0 时将列表添加到新列表中
num_group2.append(num_group1)
num_group1 = []
else:
if num_group1 not in num_group2 and len(num_group1) != 0:
num_group2.append(num_group1)
break
else:
break
return num_group2
# 整数
def integer_part(integer):
if integer == '0':
return '零元'
answer = ''
count = 0
for num_group in groupful_num():
# read_num(num_group) 转换后的数值
# figure[count] 单位
answer = read_num(num_group) + figure[count] + answer # 数值与单位拼接
count += 1
return answer.replace('零零零零零零', '零') \
.replace('零零零零零', '零') \
.replace('零零零零', '零') \
.replace('零零零', '零') \
.replace('零零', '零') \
.replace('零亿', '亿') \
.replace('零万', '万') \
.replace('零仟', '仟') \
.replace('零元', '元')
def read_num(b):
ns = ''
for x in range(1, len(b)):
num = dic_num[0][b[x]] # 转换大小写
word = num + (dic_num[x] if b[x] != '0' else '')
# 如果字符是0,添加一个''
ns = word + ns # 叠加
return ns + (dic_num[0][b[0]] if b[0] != '0' else '')
# 小数
def decimals_part(decimals):
new_deciamls = ''
for i in range(len(decimals)):
if i == 0:
new_deciamls += dic_num[0][decimals[i]]
new_deciamls += '角'
else:
new_deciamls += dic_num[0][decimals[i]]
new_deciamls += '分'
else:
new_deciamls += '整'
return new_deciamls
input_num = input("请输入不超过一万兆的金额,小数部分不超过两位:")
integer = data_num_split(input_num)[0] # 整数部分字符串分割
decimals = data_num_split(input_num)[1]
print(integer_part(integer) + decimals_part(decimals))
以上内容稍作修改,详细请看原文
作者:冬日奶茶
来源:CSDN
原文:点击进入 https://blog.csdn.net/RaimengChen/article/details/105348899