我要在此代码中添加/改进的内容是什么?是否可以在不导入num2words或inflect模块的情况下完成?我尝试将一些代码与此代码混合使用,但是它们都不起作用。
这是我对this original code.的改进代码,在此先谢谢您!
one = ['', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine']
tenp = ['Ten', 'Eleven', 'Twelve', 'Thirteen', 'Fourteen', 'Fifteen', 'Sixteen', 'Seventeen', 'Eighteen', 'Nineteen']
tenp2 = ['', '', 'Twenty', 'Thirty', 'Forty', 'Fifty', 'Sixty', 'Seventy', 'Eighty', 'Ninety']
def once(num):
word = one[int(num)]
word = word.strip()
return word
def ten(num):
if num[0] == '1':
word = tenp[int(num[1])]
else:
text = once(num[1])
word = tenp2[int(num[0])]
word = word + " " + text
word = word.strip()
return word
def hundred(num):
word = ''
text = ten(num[1:])
word = one[int(num[0])]
if num[0] != '0':
word = word + " Hundred "
word = word + text
word = word.strip()
return word
def thousand(num):
word = ''
pref = ''
text = ''
length = len(num)
if length == 6:
text = hundred(num[3:])
pref = hundred(num[:3])
if length == 5:
text = hundred(num[2:])
pref = ten(num[:2])
if length == 4:
text = hundred(num[1:])
word = one[int(num[0])]
if num[0] != '0' or num[1] != '0' or num[2] != '0':
word = word + " Thousand "
word = word + text
if length == 6 or length == 5:
word = pref + word
word = word.strip()
return word
test = int(input("Enter number(0-999,999):"))
a = str(test)
leng = len(a)
if leng == 1:
if a == '0':
num = 'Zero'
else:
num = once(a)
if leng == 2:
num = ten(a)
if leng == 3:
num = hundred(a)
if leng > 3 and leng < 7:
num = thousand(a)
print(num)
这是此代码的输出
Enter number(0-999,999):123456
One Hundred Twenty Three Thousand Four Hundred Fifty Six
我希望它像这样
Enter number(0-999,999):123456.25
One Hundred Twenty Three Thousand Four Hundred Fifty Six and 25/100
答案 0 :(得分:1)
您可以先检查小数点是否为“。”。出现在您的字符串中,如果存在则提取小数点后的数字
if '.' in a:
decimal = a.split('.')[1]
现在,您计算十进制字符串的长度,以10的幂为单位将是分母,而转换为int的字符串将是您的分子
numerator = int(decimal)
denominator = 10**len(decimal)
'{}/{}'.format(numerator, denominator)
例如对于.25,分子是int(25)= 25,而分母是10 ** len('25')= 100,所以25/100
答案 1 :(得分:0)
通常应按时间顺序读取小数位,例如pi = 3.1415 =>三点一四一五。 因此,您可以实现类似
digits = ['zero', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine']
decimal = float - int(float) #.43827812734682374
decimal = round(decimal, 4) #round to 4th place
decimal_string_list = [digits[int(i)] for i in str(decimal)[2:] ]