如何在 Python 中将数字转换为单词

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19504350/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 13:54:36  来源:igfitidea点击:

How to Convert numbers to Words in Python

pythonpython-3.x

提问by user1919840

I need to turn numbers from 1 - 99 into words. This is what I got so far:

我需要将数字从 1 - 99 转换为单词。这是我到目前为止得到的:

num2words1 = {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'}
num2words2 = ['Twenty', 'Thirty', 'Forty', 'Fifty', 'Sixty', 'Seventy', 'Eighty', 'Ninety']

def number(Number):

    if (Number > 1) or (Number < 19):
        return (num2words1[Number])
    elif (Number > 20) or (Number < 99):
        return (num2words2[Number])
    else:
        print("Number Out Of Range")
        main()

def main():
    num = eval(input("Please enter a number between 0 and 99: "))
    number(num)
main()

Now, the BIGGEST problem that I have so far is that the if, elif and else statements DO NOT seem to work. Only the first if statement runs.

现在,到目前为止我遇到的最大问题是 if、elif 和 else 语句似乎不起作用。只有第一个 if 语句运行。

The second problem is creating the string version of the numbers from 20-99....

第二个问题是创建 20-99 数字的字符串版本......

Please help, thanks in advance.

请帮忙,提前致谢。

P.S. Yes, I know about the num2word library, but I am not allowed to use it.

PS 是的,我知道 num2word 库,但我不允许使用它。

采纳答案by Martijn Pieters

Your first statement logic is incorrect. Unless Numberis 1 or smaller, that statement is alwaysTrue; 200 is greater than 1 as well.

您的第一个语句逻辑不正确。除非Number是 1 或更小,否则该语句始终为真;200 也大于 1。

Use andinstead, and include 1in the acceptable values:

改用and并包含1在可接受的值中:

if (Number >= 1) and (Number <= 19):

You could use chaining as well:

您也可以使用链接:

if 1 <= Number <= 19:

For numbers of 20 or larger, use divmod()to get both the number of tens and the remainder:

对于 20 或更大的数字,使用divmod()来获得十的数量和余数:

tens, remainder = divmod(Number, 10)

Demo:

演示:

>>> divmod(42, 10)
(4, 2)

then use those values to build your number from the parts:

然后使用这些值从零件中构建您的数字:

return num2words2[tens - 2] + '-' + num2words1[below_ten]

Don't forget to account for cases when the number is above 20 and doesn't have a remainder from the divmod operation:

不要忘记考虑数字大于 20 并且没有来自 divmod 操作的余数的情况:

return num2words2[tens - 2] + '-' + num2words1[remainder] if remainder else num2words2[tens - 2]

All put together:

全部放在一起:

def number(Number):
    if 0 <= Number <= 19:
        return num2words1[Number]
    elif 20 <= Number <= 99:
        tens, remainder = divmod(Number, 10)
        return num2words2[tens - 2] + '-' + num2words1[remainder] if remainder else num2words2[tens - 2]
    else:
        print('Number out of implemented range of numbers.')

回答by yemu

if Number > 19 and Number < 99:
    textNumber = str(Number)
    firstDigit, secondDigit = textNumber
    firstWord = num2words2[int(firstDigit)]
    secondWord = num2words1[int(secondDigit)]
    word = firstWord + secondWord 
if Number <20 and Number > 0:
    word = num2words1[Number]
if Number > 99:
    error

回答by bcollins

I've been also converting numbers to words for some fuzzy matching routines. I used a library called inflect I forked off pwdyson which worked awesome:

我也一直在将数字转换为一些模糊匹配例程的单词。我使用了一个名为 inflect 的库,我分叉了 pwdyson,它工作得很棒:

https://github.com/pwdyson/inflect.py

https://github.com/pwdyson/inflect.py

回答by dansalmo

You can make this much simpler by using one dictionary and a try/except clause like this:

您可以通过使用一个字典和一个像这样的 try/except 子句来使这变得更简单:

num2words = {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', 0: 'Zero'}

>>> def n2w(n):
        try:
            print num2words[n]
        except KeyError:
            try:
                print num2words[n-n%10] + num2words[n%10].lower()
            except KeyError:
                print 'Number out of range'

>>> n2w(0)
Zero
>>> n2w(13)
Thirteen        
>>> n2w(91)
Ninetyone
>>> n2w(21)
Twentyone
>>> n2w(33)
Thirtythree

回答by Jake

recursively:

递归地:

num2words = {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'}
num2words2 = ['Twenty', 'Thirty', 'Forty', 'Fifty', 'Sixty', 'Seventy', 'Eighty', 'Ninety']
def spell(num):
    if num == 0:
        return ""
    if num < 20:
        return (num2words[num])
    elif num < 100:
        ray = divmod(num,10)
        return (num2words2[ray[0]-2]+" "+spell(ray[1]))
    elif num <1000:
        ray = divmod(num,100)
        if ray[1] == 0:
            mid = " hundred"
        else:
            mid =" hundred and "
        return(num2words[ray[0]]+mid+spell(ray[1]))

回答by CQ92

import math

number = int(input("Enter number to print: "))

number_list = ["zero","one","two","three","four","five","six","seven","eight","nine"]
teen_list = ["ten","eleven","twelve","thirteen","fourteen","fifteen","sixteen","seventeen","eighteen","nineteen"]
decades_list =["twenty","thirty","forty","fifty","sixty","seventy","eighty","ninety"]


if number <= 9:
    print(number_list[number].capitalize())
elif number >= 10 and number <= 19:
    tens = number % 10
    print(teen_list[tens].capitalize())
elif number > 19 and number <= 99:
    ones = math.floor(number/10)
    twos = ones - 2
    tens = number % 10
    if tens == 0:
        print(decades_list[twos].capitalize())
    elif tens != 0:
        print(decades_list[twos].capitalize() + " " + number_list[tens])

回答by Ajesh DS

This Did the job for me(Python 2.x)

这对我有用(Python 2.x)

nums = {1:"One", 2:"Two", 3:"Three" ,4:"Four", 5:"Five", 6:"Six", 7:"Seven", 8:"Eight",\
        9:"Nine", 0:"Zero", 10:"Ten", 11:"Eleven", 12:"Tweleve" , 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"}
num = input("Enter a number: ")
# To convert three digit number into words 
if 100 <= num < 1000:
    a = num / 100
    b = num % 100
    c = b / 10
    d = b % 10
    if c == 1 :
        print nums[a] + "hundred" , nums[b]
    elif c == 0:
        print nums[a] + "hundred" , nums[d]
    else:
        c *= 10
        if d == 0:
            print nums[a] + "hundred", nums[c]
        else:
            print nums[a] + "hundred" , nums[c], nums[d]
# to convert two digit number into words            
elif 0 <= num < 100:
    a = num / 10
    b = num % 10
    if a == 1:
        print nums[num]
    else:
        a *= 10
        print nums[a], nums[b]

回答by user3515136

    def giveText(num):
    pairs={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:'fourty',50:'fifty',60:'sixty',70:'seventy',80:'eighty',90:'ninety',0:''} # this and above 2 lines are actually single line
    return pairs[num]

def toText(num,unit):
    n=int(num)# this line can be removed
    ans=""
    if n <=20:
        ans= giveText(n)
    else:
        ans= giveText(n-(n%10))+" "+giveText((n%10))
    ans=ans.strip()
    if len(ans)>0:
        return " "+ans+" "+unit
    else:
        return " "

num="99,99,99,999"# use raw_input()
num=num.replace(",","")# to remove ','
try:
    num=str(int(num)) # to check valid number
except:
    print "Invalid"
    exit()

while len(num)<9: # i want fix length so no need to check it again
    num="0"+num

ans=toText( num[0:2],"Crore")+toText(num[2:4],"Lakh")+toText(num[4:6],"Thousand")+toText(num[6:7],"Hundred")+toText(num[7:9],"")
print ans.strip()

回答by Emmanuel Mtali

Use python library called num2wordsLink -> HERE

使用名为num2wordsLink -> HERE 的python 库

回答by Srinivas Balina

num2words = {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', 0: 'Zero'}
  def n2w(n):
    try:
      return num2words[n]
    except KeyError:
      try:
        return num2words[n-n%10] + num2words[n%10].lower()
      except KeyError:
        try:
          if(n>=100 and n<=999):
            w=''
            w=w+str(n2w(int(n/100)))+'Hundred'
            n=n-(int(n/100)*100)
            if(n>0):
              w=w+'And'+n2w(n)
            return w    
          elif(n>=1000):
            w=''
            w=w+n2w(int(n/1000))+'Thousand'
            n=n-int((n/1000))*1000
            if(n>0 and n<100):
              w=w+'And'+n2w(n)
            if(n>=100):
              w=w+n2w(int(n/100))+'Hundred'
              n=n-(int(n/100)*100)
              if(n>0):
                w=w+'And'+n2w(n)
            return w
        except KeyError:
            return 'Ayyao'
  for i in range(0,99999):
    print(n2w(i))