将Python整数转换为单词

2024-05-16 04:48:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我写了下面的代码,假设将所有数字从1到9999转换成单词,但我正在超出范围的数字,如111等。请帮助。谢谢。在

global n2W
n2W = {1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five',\
        6: 'six', 7: 'seven', 8: 'eight', 9: 'nine', 10: 'ten', \
        11: 'eleven', 12: 'twelve', 13: 'thirteen', 14: 'fourteen', \
        15: 'fifteen', 16: 'sixteen', 17: 'seventeen', 18: 'eighteen',\
        19: 'nineteen',20:'twenty', 30:'thirty', 40:'forty', 50:'fifty', 60:'sixty',\
        70: 'seventy', 80:'eighty', 90:'ninety',100:'one hundred', 200:'two hundred',\
        300:'three hundred', 400:'four hundred',500:'five hundred', 600:'six hundred',\
        700:'seven hundred',800:'eight hundred', 900:'nine hundred',\
        1000:'one thousand', 2000:'two thousand', 3000:'three thousand',\
        5000:'five thousand', 6000:'six thousand', 7000:'seven thousand',\
        8000:'eight thousand', 9000:'nine thousand',10000:'ten thousand'}


def num2Word(n):
    try:
        print (n2W[n])
    except KeyError:

        try:
            print (n2W[n-n%10] , n2W[n%10].lower())
        except KeyError:
            print ("Number out of range")

n = eval(input("Please enter a number between 1 and 9999 inclusive: "))
num2Word(n)

Tags: 数字onethreefourprintfivetwothousand
3条回答

看看这个解决方案,在这个方案中,我们从左到右迭代数字位数,在每次迭代中将value映射到文本,然后放弃最有效的数字。在

def num2Word(n):
    try:
        word = ''
        c = 1000
        while n:
            value = (n//c)*c if n > c else None
            n %= c
            c /= 10
            if value is not None:
                word += '%s ' % n2W[value] 
    except KeyError:
        print ("Number out of range")
    return word 

 n = eval(input("Please enter a number between 1 and 9999 inclusive: "))
 print num2Word(n)


例如,对于n=1234,我们将有四次迭代,其中value等于:

value=1000
value=200
value=30
value=4

你只尝试一次,这意味着这将工作最多2位数。试着递归地做。如果你想要,我可以给你一个有效的答案。 不要执行n2W[n%10].lower(),而是使用对num2Word的递归调用。在

只需手动插入一个数字就可以看出为什么会出错

例如,尝试n=111

(n2W[n-n%10] , n2W[n%10].lower())

111%10=1,因此您有:

n2W[110]和{}

n2W[110]是你的关键错误,它只需要递归到你的函数中。在

相关问题 更多 >