题目大概是这样:一个数字范围小雨10000,输出它的国语发音:如1204 -> 一万两百零四。
欢迎更正。
转载注明原文链接。
#!/usr/bin/env python3
import sys
chars = ['', '十', '百', '千', '万']
m = {'0': '零', '1' : '一', '2' : '二', '3' : '三', '4' : '四',
'5' : '五', '6' : '六', '7' : '七', '8' : '八', '9' : '九'}
def num2txt(num):
# 首先翻转字符串, ‘数字’403 -> ‘字符串’304
numStr = str(num)
l = []
for i in numStr:
l.insert(0, i)
numStr = ''.join(l)
l = []
marked = False # 第一个低位零是否已经标记过
for i, s in enumerate(numStr):
if i == 0:
if not s == '0':
l.append(m[s])
else:
if s == '0' and not marked:
if l and not l[-1] == '0':
marked = True
l.append(m['0'])
elif s == '0': # 已经标过第一个零,高位零不标记
continue
else:
l.append(chars[i])
l.append(m[s])
return l
def main():
num = input('please input the number: ')
l = num2txt(num)
for i in range(len(l)):
print(l[-1], end='')
l.pop()
print()
main()