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

时间:2013-10-21 20:45:42

标签: python python-3.x

我需要将数字从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()

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

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

请提前帮助,谢谢。

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

22 个答案:

答案 0 :(得分:11)

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

改为使用and,并在可接受的值中包含1

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

您也可以使用链接:

if 1 <= Number < 19:

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

tens, below_ten = divmod(Number, 10)

演示:

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

然后使用这些值从部分构建您的号码:

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

全部放在一起:

def number(Number):
    if 1 <= Number < 19:
        return num2words1[Number]
    elif 20 <= Number <= 99:
        tens, below_ten = divmod(Number, 10)
        return num2words2[tens - 2] + '-' + num2words1[below_ten]
    else:
        print("Number out of range")

答案 1 :(得分:11)

通过使用一个字典和一个像这样的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

答案 2 :(得分:6)

使用名为num2words的python库 链接 - &gt; HERE

答案 3 :(得分:3)

您是否可以使用其他套餐?这个对我很有用: Inflect。它对自然语言生成很有用,并且有一种将数字转换成英文文本的方法。

我用

安装了它
$ pip install inflect

然后在你的Python会话中

>>> import inflect
>>> p = inflect.engine()
>>> p.number_to_words(1234567)
'one million, two hundred and thirty-four thousand, five hundred and sixty-seven'

>>> p.number_to_words(22)
'twenty-two'

答案 4 :(得分:2)

代码2和3:

ones = {
    0: '', 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'}
tens = {
    2: 'twenty', 3: 'thirty', 4: 'forty', 5: 'fifty', 6: 'sixty',
    7: 'seventy', 8: 'eighty', 9: 'ninety'}
illions = {
    1: 'thousand', 2: 'million', 3: 'billion', 4: 'trillion', 5: 'quadrillion',
    6: 'quintillion', 7: 'sextillion', 8: 'septillion', 9: 'octillion',
    10: 'nonillion', 11: 'decillion'}



def say_number(i):
    """
    Convert an integer in to it's word representation.

    say_number(i: integer) -> string
    """
    if i < 0:
        return _join('negative', _say_number_pos(-i))
    if i == 0:
        return 'zero'
    return _say_number_pos(i)


def _say_number_pos(i):
    if i < 20:
        return ones[i]
    if i < 100:
        return _join(tens[i // 10], ones[i % 10])
    if i < 1000:
        return _divide(i, 100, 'hundred')
    for illions_number, illions_name in illions.items():
        if i < 1000**(illions_number + 1):
            break
    return _divide(i, 1000**illions_number, illions_name)


def _divide(dividend, divisor, magnitude):
    return _join(
        _say_number_pos(dividend // divisor),
        magnitude,
        _say_number_pos(dividend % divisor),
    )


def _join(*args):
    return ' '.join(filter(bool, args))

测试:

def test_say_number(data, expected_output):
    """Test cases for say_number(i)."""
    output = say_number(data)
    assert output == expected_output, \
        "\n    for:      {}\n    expected: {}\n    got:      {}".format(
            data, expected_output, output)


test_say_number(0, 'zero')
test_say_number(1, 'one')
test_say_number(-1, 'negative one')
test_say_number(10, 'ten')
test_say_number(11, 'eleven')
test_say_number(99, 'ninety nine')
test_say_number(100, 'one hundred')
test_say_number(111, 'one hundred eleven')
test_say_number(999, 'nine hundred ninety nine')
test_say_number(1119, 'one thousand one hundred nineteen')
test_say_number(999999,
                'nine hundred ninety nine thousand nine hundred ninety nine')
test_say_number(9876543210,
                'nine billion eight hundred seventy six million '
                'five hundred forty three thousand two hundred ten')
test_say_number(1000**1, 'one thousand')
test_say_number(1000**2, 'one million')
test_say_number(1000**3, 'one billion')
test_say_number(1000**4, 'one trillion')
test_say_number(1000**5, 'one quadrillion')
test_say_number(1000**6, 'one quintillion')
test_say_number(1000**7, 'one sextillion')
test_say_number(1000**8, 'one septillion')
test_say_number(1000**9, 'one octillion')
test_say_number(1000**10, 'one nonillion')
test_say_number(1000**11, 'one decillion')
test_say_number(1000**12, 'one thousand decillion')
test_say_number(
    1-1000**12,
    'negative nine hundred ninety nine decillion nine hundred ninety nine '
    'nonillion nine hundred ninety nine octillion nine hundred ninety nine '
    'septillion nine hundred ninety nine sextillion nine hundred ninety nine '
    'quintillion nine hundred ninety nine quadrillion nine hundred ninety '
    'nine trillion nine hundred ninety nine billion nine hundred ninety nine'
    ' million nine hundred ninety nine thousand nine hundred ninety nine')

答案 5 :(得分:1)

我也一直在为一些模糊匹配例程将数字转换为单词。我使用了一个名为inflect的库,我将pwdyson分离出来,效果很棒:

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

答案 6 :(得分:1)

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])

答案 7 :(得分:1)

将数字转换为单词:
这是一个使用字典将数字转换成单词的示例。

string = input("Enter a string: ")
my_dict = {'0': 'zero', '1': 'one', '2': 'two', '3': 'three', '4': 'four', '5': 'five', '6': 'six', '7': 'seven', '8': 'eight', '9': 'nine'}
for item in string:
  if item in my_dict.keys():
    string = string.replace(item, my_dict[item])
print(string)

Output

答案 8 :(得分:1)

single_digit = {0: 'zero', 1: 'one', 2: 'two', 3: 'three', 4: 'four', 
            5: 'five', 6: 'six', 7: 'seven', 8: 'eight',
            9: 'nine'}

teen = {10: 'ten', 11: 'eleven', 12: 'twelve', 13: 'thirteen', 
        14: 'fourteen', 15: 'fifteen', 16: 'sixteen',
        17: 'seventeen', 18: 'eighteen', 19: 'nineteen'}

tens = {20: 'twenty', 30: 'thirty', 40: 'forty', 50: 'fifty', 60: 'sixty', 
        70: 'seventy', 80: 'eighty', 90: 'ninety'}

def spell_single_digit(digit):
    if 0 <= digit < 10:
        return single_digit[digit]

def spell_two_digits(number):
    if 10 <= number < 20:
        return teen[number]

    if 20 <= number < 100:
        div = (number // 10) * 10
        mod = number % 10
        if mod != 0:
            return tens[div] + "-" + spell_single_digit(mod)
        else:
            return tens[number]

def spell_three_digits(number):
    if 100 <= number < 1000:
        div = number // 100
        mod = number % 100
        if mod != 0:
            if mod < 10:
                return spell_single_digit(div) + " hundred " +  \
                   spell_single_digit(mod)
            elif mod < 100:
                return spell_single_digit(div) + " hundred " + \
                   spell_two_digits(mod)
        else:
            return spell_single_digit(div) + " hundred"

def spell(number):
    if -1000000000 < number < 1000000000:
        if number == 0:
            return spell_single_digit(number)
        a = ""
        neg = False
        if number < 0:
            neg = True
            number *= -1
        loop = 0
        while number:
            mod = number % 1000
            if mod != 0:
                c = spell_three_digits(mod) or spell_two_digits(mod) \
                    or spell_single_digit(mod)
                if loop == 0:
                    a = c + " " + a
                elif loop == 1:
                    a = c + " thousand " + a
                elif loop == 2:
                    a = c + " million " + a
            number = number // 1000
            loop += 1
        if neg:
            return "negative " + a
        return a

答案 9 :(得分:0)

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

答案 10 :(得分:0)

def convert(num):
    # started as grepit's version at https://stackoverflow.com/a/54002579/746054
    # large constants converted to exponential notation
    # orders of magnitude (oom) added
    # overflow message
    units = (
        "", "one ", "two ", "three ", "four ", "five ", "six ", "seven ", "eight ", "nine ", "ten ", "eleven ",
        "twelve ",
        "thirteen ", "fourteen ", "fifteen ", "sixteen ", "seventeen ", "eighteen ", "nineteen ")
    tens = ("", "", "twenty ", "thirty ", "forty ", "fifty ", "sixty ", "seventy ", "eighty ", "ninety ")
    oom = ('thousand', 'million', 'billion', 'trillion', 'quadrillion', 'quintillion', 'sextillion', 'septillion',
           'octillion', 'nonillion', 'decillion', 'undecillion', 'duodecillion', 'tredecillion', 'quattuordecillion',
           'quindecillion', 'sexdecillion', 'septendecillion', 'octodecillion', 'novemdecillion', 'vigintillion')

    if num < 0:
        return "minus " + convert(-num)

    if num < 20:
        return units[num]

    if num < 100:
        return tens[num // 10] + units[num % 10]

    if num < 10 ** 3:
        return units[num // 10 ** 2] + "hundred " + convert(num % 10 ** 2)

    for idx, name in enumerate(oom):
        scale = (idx + 1) * 3
        cap = scale + 3
        if num < 10 ** cap:
            return convert(num // 10 ** scale) + name + " " + convert(num % 10 ** scale)

    return "function " + convert.__name__ + " has exhausted its vocabulary"

答案 11 :(得分:0)


class amount_to_words:
    """
    Maintain a dictionary for integers from 1 to 20 and then 30,40 etc as they cant be derived.
    Add denominations into the given dictionary .
    """

    def __init__(
        self,
        dc={
            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: "tirty",
            40: "forty",
            50: "fifty",
            60: "sixty",
            70: "seventy",
            80: "eighty",
            90: "ninety",
        },
        denominations={
            10000000: "crore",
            100000: "lack",
            1000: "thousand",
            100: "hundred",
        },
    ):
        self.dc = dc
        self.denominations = denominations

    """
    returns length of the number
    """

    def get_len(self, num):
        return len(str(num))

    """
    A recursive function to convert number to words.
    The idea is when you divide and get a modulus by one of the denomination,
    It might not be in the simplest and basic form ,hence deduce them /call recursively until you arrive 
    at the base conditions which is when the length of the number is one or two we can 
    directly get the values from the dictionary
    """

    def convert(self, num):
        if num:

            if self.get_len(num) == 1:
                
                return self.dc[num % 10]

            elif self.get_len(num) == 2:
                if num <= 20:
                    return self.dc[num]

                return self.dc[num // 10 * 10] + " " + self.dc.get(num % 10, "")

            else:
                for d in self.denominations:
                    res = num // d
                    if res:
                        #convert the previous part and the final part and join them
                        return f"{self.convert(res)} {self.denominations[d]} {self.convert(num%d)}"
        return ""

您可以按照惯例更改面额,这将适用于您想要输入的大数字

答案 12 :(得分:0)

您可以通过这种方式执行此程序。范围在0到99,999之间

import { CustomValidators } from 'ng2-validation';
    //add or remove validator dynamically

    onRoleChange($role ){
    if(role == 'admin')
   { this.resetPwdForm.get('newpwdctrlname').setValidators([Validators.min(3),Validators.required]);
}
else if(role == 'not admin'){
this.resetPwdForm.get('ewpwdctrlname').setValidators([Validators.required, Validators.pattern('<Pattern>'), CustomValidators.equalTo(password]);
}

    }

答案 13 :(得分:0)


    number=input("number")
    numls20={"1":"one","2":"two","3":"three","4":"four","5":"five","6":"six","7":"seven","8":"eight","9":"nine","10":"ten","11":"elevn","12":"twelve","13":"thirteen","14":"fourteen","15":"fifteen","16":"sixteen","17":"seventeen","18":"eighteen","19":"ninteen"}
    numls100={"1":"ten","2":"twenty","3":"thrity","4":"fourty","5":"fifty","6":"sixty","7":"seventy","8":"eighty","9":"ninty"}
    numls1000={"1":"hundred","2":"twohundred","3":"threehundred","4":"fourhundred","5":"fivehundred","6":"sixhundred","7":"sevenhundred","8":"eighthundred","9":"ninehundred"}    
    def num2str(number):
        if (int(number)<20):
            print(numls20[number])
        elif(int(number)<100):
            print(numls100[number[0]]+" "+numls20[number[1]])
        elif(int(number)<1000):
            if ((int(number))%100 == 0):
                print(numls1000[number[0]])
            else:
                print(numls1000[number[0]]+" and "+numls100[number[1]]+" "+numls20[number[2]])
        elif(int(number)<10000):
            if ((int(number))%1000 == 0):
                print(numls20[number[0]]+" thousand")
            elif(int(number)%100 == 0):
                print(numls20[number[0]]+" thousand "+numls1000[number[1]])
            elif(int(number)%10 == 0):
                print(numls20[number[0]]+" thousand "+numls1000[number[1]]+" and "+numls100[number[2]])
            else:
                print(numls20[number[0]]+" thousand "+numls1000[number[1]]+" and "+numls100[number[2]]+" "+numls20[number[3]])
    num2str(number)

答案 14 :(得分:0)

我知道这是一个非常古老的职位,我参加聚会可能已经很晚了,但是希望这会对其他人有所帮助。 这对我有用。

phone_words = input('Phone: ')
numbered_words = {
    '0': 'zero',
    '1': 'one',
    '2': 'two',
    '3': 'three',
    '4': 'four',
    '5': 'five',
    '6': 'six',
    '7': 'seven',
    '8': 'eight',
    '9': 'nine'
}
output = ""
for ch in phone_words:
    output += numbered_words.get(ch, "!") + " "
phone_words = numbered_words

print(output)

答案 15 :(得分:0)

许多人已经正确回答了这个问题,但这是另一种方法,它实际上不仅覆盖了1-99,而且实际上超出了任何数据范围,但不覆盖小数。

注意:这已使用python 3.7进行了测试

def convert(num):
    units = ("", "one ", "two ", "three ", "four ","five ", "six ", "seven ","eight ", "nine ", "ten ", "eleven ", "twelve ", "thirteen ", "fourteen ", "fifteen ","sixteen ", "seventeen ", "eighteen ", "nineteen ")
    tens =("", "", "twenty ", "thirty ", "forty ", "fifty ","sixty ","seventy ","eighty ","ninety ")

    if num < 0:
        return "minus "+convert(-num)

    if num<20:
        return  units[num] 

    if num<100:

        return  tens[num // 10]  +units[int(num % 10)] 

    if num<1000:
        return units[num // 100]  +"hundred " +convert(int(num % 100))

    if num<1000000: 
        return  convert(num // 1000) + "thousand " + convert(int(num % 1000))

    if num < 1000000000:    
        return convert(num // 1000000) + "million " + convert(int(num % 1000000))

    return convert(num // 1000000000)+ "billion "+ convert(int(num % 1000000000))


print(convert(100001333))

enter image description here

答案 16 :(得分:0)

def nums_to_words(string):
    string = int(string) # Convert the string to an integer
    one_ten=['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 
    'eight', 'nine']
    ten_nineteen=['ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 
    'fifteen',
    'sixteen', 'seventeen', 'eighteen', 'nineteen']
    twenty_ninety=[' ', ' ','twenty', 'thirty', 'forty', 'fifty', 'sixty', 
    'seventy', 'eighty',
    'ninety']
    temp_str = ""
    if string == 0: # If the string given equals to 0
        temp_str = 'zero ' # Assign the word zero to the var temp_str
    # Do the calculation to find each digit of the str given
    first_digit = string // 1000
    second_digit = (string % 1000) // 100
    third_digit = (string % 100) // 10
    fourth_digit = (string % 10)
    if first_digit > 0: 
        temp_str = temp_str + one_ten[first_digit] + ' thousand '
    # one_ten[first_digit] gets you the number you need from one_ten and you add thousand (since we're trying to convert to words ofc)
    # You do the same for the rest...
    if second_digit > 0:
        temp_str = temp_str + one_ten[second_digit] + ' hundred '
    if third_digit > 1:
        temp_str = temp_str + twenty_ninety[third_digit] + " "
    if third_digit == 1:
        temp_str = temp_str + ten_nineteen[fourth_digit] + " "
    else:
        if fourth_digit:
            temp_str = temp_str + one_ten[fourth_digit] + " "
    if temp_str[-1] == " ": # If the last index is a space
        temp_str = temp_str[0:-1] # Slice it 
return temp_str 

希望您对代码有更好的了解; 如果还是不明白,请告诉我,以便尽我所能。

答案 17 :(得分:0)

    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()

答案 18 :(得分:0)

这是我的工作(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]

答案 19 :(得分:0)

递归:

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]))

答案 20 :(得分:-2)

num2words1 = {1: 'One', 2: 'Two', 3: 'Three', 4: 'Four', 5: 'Five', 
            6: 'Six', 7: 'Seven', 8: 'Eight', 9: 'Nine', 0:"Zero"}

num = input("Enter a Number")
for i in num:
    print(num2words1[(int)(i)],end=" ")

答案 21 :(得分:-3)

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))