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

Lgm*_*ken 47 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
Run Code Online (Sandbox Code Playgroud)

但我无法弄清楚如何编写程序,以便显示单词(即九十九,九十八等)而不是数字.

我一直令人头我的头在Python书我有,我明白,也许我只是不明白for/ if/ elif/ else循环,但是我只是纺纱我的车轮.

谁能提供任何见解?我不是在寻找一个直接的答案,虽然这可能有助于我看到我的问题,只要指出我正确方向的任何事情都会很棒.

Lee*_*Lee 61

inflect包可以做到这一点.

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

$ pip install inflect
Run Code Online (Sandbox Code Playgroud)

然后:

>>>import inflect
>>>p = inflect.engine()
>>>p.number_to_words(99)
ninety-nine
Run Code Online (Sandbox Code Playgroud)


ran*_*dra 35

使用可在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'
Run Code Online (Sandbox Code Playgroud)

  • 该软件包已被[`num2words`](https://pypi.python.org/pypi/num2words)取代. (10认同)

Dev*_*per 20

我们改编了一个现有的解决方案(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)
Run Code Online (Sandbox Code Playgroud)

结果:

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
Run Code Online (Sandbox Code Playgroud)

请注意,它适用于整数.然而,将浮点数除以两个整数部分是微不足道的.


SiL*_*oNG 17

这是在Python 3中实现它的一种方法:

"""Given an int32 number, print it in English."""
def int_to_en(num):
    d = { 0 : 'zero', 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' }
    k = 1000
    m = k * 1000
    b = m * 1000
    t = b * 1000

    assert(0 <= num)

    if (num < 20):
        return d[num]

    if (num < 100):
        if num % 10 == 0: return d[num]
        else: return d[num // 10 * 10] + '-' + d[num % 10]

    if (num < k):
        if num % 100 == 0: return d[num // 100] + ' hundred'
        else: return d[num // 100] + ' hundred and ' + int_to_en(num % 100)

    if (num < m):
        if num % k == 0: return int_to_en(num // k) + ' thousand'
        else: return int_to_en(num // k) + ' thousand, ' + int_to_en(num % k)

    if (num < b):
        if (num % m) == 0: return int_to_en(num // m) + ' million'
        else: return int_to_en(num // m) + ' million, ' + int_to_en(num % m)

    if (num < t):
        if (num % b) == 0: return int_to_en(num // b) + ' billion'
        else: return int_to_en(num // b) + ' billion, ' + int_to_en(num % b)

    if (num % t == 0): return int_to_en(num // t) + ' trillion'
    else: return int_to_en(num // t) + ' trillion, ' + int_to_en(num % t)

    raise AssertionError('num is too large: %s' % str(num))
Run Code Online (Sandbox Code Playgroud)

结果是:

0 zero
3 three
10 ten
11 eleven
19 nineteen
20 twenty
23 twenty-three
34 thirty-four
56 fifty-six
80 eighty
97 ninety-seven
99 ninety-nine
100 one hundred
101 one hundred and one
110 one hundred and ten
117 one hundred and seventeen
120 one hundred and twenty
123 one hundred and twenty-three
172 one hundred and seventy-two
199 one hundred and ninety-nine
200 two hundred
201 two hundred and one
211 two hundred and eleven
223 two hundred and twenty-three
376 three hundred and seventy-six
767 seven hundred and sixty-seven
982 nine hundred and eighty-two
999 nine hundred and ninety-nine
1000 one thousand
1001 one thousand, one
1017 one thousand, seventeen
1023 one thousand, twenty-three
1088 one thousand, eighty-eight
1100 one thousand, one hundred
1109 one thousand, one hundred and nine
1139 one thousand, one hundred and thirty-nine
1239 one thousand, two hundred and thirty-nine
1433 one thousand, four hundred and thirty-three
2000 two thousand
2010 two thousand, ten
7891 seven thousand, eight hundred and ninety-one
89321 eighty-nine thousand, three hundred and twenty-one
999999 nine hundred and ninety-nine thousand, nine hundred and ninety-nine
1000000 one million
2000000 two million
2000000000 two billion
Run Code Online (Sandbox Code Playgroud)


kin*_*all 10

嗯,简单的方法就是列出你感兴趣的所有数字:

numbers = ["zero", "one", "two", "three", "four", "five", ... 
           "ninety-eight", "ninety-nine"]
Run Code Online (Sandbox Code Playgroud)

(...表示你在哪里键入其他数字的文本表示.不,Python不会为你神奇地填充它,你必须键入所有这些才能使用该技术.)

然后打印数字,只需打印numbers[i].十分简单.

当然,该列表是很多打字,所以你可能想知道一个简单的方法来生成它.不幸的是,英语有很多不规则因此你必须手动输入前20(0-19),但你可以使用规律来生成其余的99.(你也可以生成一些青少年,但只有其中一些,所以输入它们似乎最容易.)

numbers = "zero one two three four five six seven eight nine".split()
numbers.extend("ten eleven twelve thirteen fourteen fifteen sixteen".split())
numbers.extend("seventeen eighteen nineteen".split())
numbers.extend(tens if ones == "zero" else (tens + "-" + ones) 
    for tens in "twenty thirty forty fifty sixty seventy eighty ninety".split()
    for ones in numbers[0:10])

print numbers[42]  # "forty-two"
Run Code Online (Sandbox Code Playgroud)

另一种方法是编写一个函数,每次将正确的字符串放在一起.同样,你必须对前20个数字进行硬编码,但之后你可以根据需要从头开始轻松生成它们.这将使用少的内存(一个很多少,一旦你开始有较大的数字工作).


Col*_*iza 5

您可以使用python-n2w库,只需这样做

pip install n2w
Run Code Online (Sandbox Code Playgroud)

然后简单地

print(n2w.convert(your-number-here))
Run Code Online (Sandbox Code Playgroud)


Hun*_*_71 5

我的解决方案来了:)它是各种早期的解决方案,但是是我自己开发的 - 也许有人比其他提议更喜欢它。

TENS = {30: 'thirty', 40: 'forty', 50: 'fifty', 60: 'sixty', 70: 'seventy', 80: 'eighty', 90: 'ninety'}
ZERO_TO_TWENTY = (
    'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten',
    'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen', 'twenty'
)

def number_to_english(n):
    if any(not x.isdigit() for x in str(n)):
        return ''

    if n <= 20:
        return ZERO_TO_TWENTY[n]
    elif n < 100 and n % 10 == 0:
        return TENS[n]
    elif n < 100:
        return number_to_english(n - (n % 10)) + ' ' + number_to_english(n % 10)
    elif n < 1000 and n % 100 == 0:
        return number_to_english(n / 100) + ' hundred'
    elif n < 1000:
        return number_to_english(n / 100) + ' hundred ' + number_to_english(n % 100)
    elif n < 1000000:
        return number_to_english(n / 1000) + ' thousand ' + number_to_english(n % 1000)

    return ''
Run Code Online (Sandbox Code Playgroud)

它是递归解决方案,可以轻松扩展为更大的数字


Jer*_*y D 0

您必须使用字典/数组。例如 :

 to_19= ['zero','one','two','three','four','five','six','seven','eight','nine'..'nineteen']
 tens = ['twenty'...'ninety']
Run Code Online (Sandbox Code Playgroud)

您可以通过执行以下操作来生成数字字符串:

 if len(str(number)) == 2 and  number > 20:
       word_number = tens[str(number)[0]]+' '+units[str(number)[0]]
Run Code Online (Sandbox Code Playgroud)

您必须检查最后一个数字是否不是零等等......经典的值检查。

它提醒了一个项目欧拉挑战(问题17)..你应该尝试找到一些关于它的解决方案

希望能帮助到你