如何告诉Python将整数转换为单词

2024-05-15 10:10:13 发布

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

我试图告诉Python将整数转换成单词。

示例:(使用墙上的99瓶啤酒)

我用这段代码编写了程序:

for i in range(99,0,-1):
    print i, "Bottles of beer on the wall,"
    print i, "bottles of beer."
    print "Take one down and pass it around,"
    print i-1, "bottles of beer on the wall."
    print

但我不知道如何编写程序,以便显示单词(即九十九、九十八等)而不是数字。

我在python的书中绞尽脑汁,我明白也许我还不明白for/if/elif/else循环,但我只是在旋转我的轮子。

有人能提供一些见解吗?我不是在寻找一个直接的答案,虽然这可能有助于我看到我的问题,只是任何东西都可以给我指出正确的方向将是伟大的。


Tags: ofthe代码in程序示例foron
3条回答

屈折包可以做到这一点。

https://pypi.python.org/pypi/inflect

$ pip install inflect

然后:

>>>import inflect
>>>p = inflect.engine()
>>>p.number_to_words(99)
ninety-nine

使用可以在sourceforge找到的pynum2word模块

>>> import num2word
>>> num2word.to_card(15)
'fifteen'
>>> num2word.to_card(55)
'fifty-five'
>>> num2word.to_card(1555)
'one thousand, five hundred and fifty-five'

我们采用了一个现有的很好的解决方案(ref)将数字转换为单词,如下所示:

def numToWords(num,join=True):
    '''words = {} convert an integer number into words'''
    units = ['','one','two','three','four','five','six','seven','eight','nine']
    teens = ['','eleven','twelve','thirteen','fourteen','fifteen','sixteen', \
             'seventeen','eighteen','nineteen']
    tens = ['','ten','twenty','thirty','forty','fifty','sixty','seventy', \
            'eighty','ninety']
    thousands = ['','thousand','million','billion','trillion','quadrillion', \
                 'quintillion','sextillion','septillion','octillion', \
                 'nonillion','decillion','undecillion','duodecillion', \
                 'tredecillion','quattuordecillion','sexdecillion', \
                 'septendecillion','octodecillion','novemdecillion', \
                 'vigintillion']
    words = []
    if num==0: words.append('zero')
    else:
        numStr = '%d'%num
        numStrLen = len(numStr)
        groups = (numStrLen+2)/3
        numStr = numStr.zfill(groups*3)
        for i in range(0,groups*3,3):
            h,t,u = int(numStr[i]),int(numStr[i+1]),int(numStr[i+2])
            g = groups-(i/3+1)
            if h>=1:
                words.append(units[h])
                words.append('hundred')
            if t>1:
                words.append(tens[t])
                if u>=1: words.append(units[u])
            elif t==1:
                if u>=1: words.append(teens[u])
                else: words.append(tens[t])
            else:
                if u>=1: words.append(units[u])
            if (g>=1) and ((h+t+u)>0): words.append(thousands[g]+',')
    if join: return ' '.join(words)
    return words

#example usages:
print numToWords(0)
print numToWords(11)
print numToWords(110)
print numToWords(1001000025)
print numToWords(123456789012)

结果:

zero
eleven
one hundred ten
one billion, one million, twenty five
one hundred twenty three billion, four hundred fifty six million, seven hundred
eighty nine thousand, twelve

注意,它适用于整数。尽管如此,将一个浮点数分成两个整数部分并不重要。

相关问题 更多 >