如何将w /或w / o十进制数转换为单词// Python [关闭]

问题描述 投票:-2回答:2

我将要添加/改进此代码?可以在不导入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
python python-3.x numbers word
2个回答
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


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:]  ] 
© www.soinside.com 2019 - 2024. All rights reserved.