27

我需要将数字从 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 的数字的字符串版本......

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

4

24 回答 24

27

您可以通过使用一个字典和一个 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
于 2013-10-21T23:56:39.243 回答
22

你可以使用其他包吗?这对我来说非常有效: 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'
于 2018-03-27T19:36:25.870 回答
18

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

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

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

您也可以使用链接:

if 1 <= Number <= 19:

对于 20 或更大divmod()的数字,用于获取十位数和余数:

tens, remainder = divmod(Number, 10)

演示:

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

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

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

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

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

全部放在一起:

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.')
于 2013-10-21T20:47:56.887 回答
9

num2words 使用名为Link -> HERE的 python 库

于 2017-03-02T12:09:09.593 回答
9

代码 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')
于 2019-01-03T07:42:21.170 回答
2

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

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

于 2013-10-21T22:14:27.803 回答
2
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])
于 2015-09-02T13:49:00.747 回答
2
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
于 2020-07-01T22:22:06.657 回答
1

许多人已经正确回答了这个问题,但这是另一种方式,它实际上不仅涵盖 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))

在此处输入图像描述

于 2019-01-02T07:13:49.390 回答
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)

输出

于 2020-08-14T09:24:06.030 回答
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
于 2013-10-21T20:54:57.357 回答
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]))
于 2014-01-07T01:34:55.623 回答
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]
于 2015-09-23T16:38:01.597 回答
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()
于 2017-02-06T06:07:14.577 回答
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 

我希望你对代码的理解稍微好一点;如果仍然不理解,请告诉我,以便我尽我所能提供帮助。

于 2018-06-25T10:11:05.907 回答
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)
于 2020-02-23T15:55:00.037 回答
0

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

def num_to_word(num):
    word_num = { "0": "zero", "00": "", "1" : "One" , "2" : "Two", "3" : "Three", "4" : "Four", "5" : "Five","6" : "Six", "7": "Seven", "8" : "eight", "9" : "Nine","01" : "One" , "02" : "Two", "03" : "Three", "04" : "Four", "05" : "Five","06" : "Six", "07": "Seven", "08" : "eight", "09" : "Nine", "10" : "Ten", "11": "Eleven", "12" :"Twelve", "13" : "Thirteen", "14" : "Fourteen", "15" : "Fifteen", "17":"Seventeen", "18" :"Eighteen", "19": "Nineteen", "20" : "Twenty", "30" : "Thirty", "40" : "Forty", "50" : "Fifty", "60" : "Sixty", "70": "seventy", "80" : "eighty", "90" : "ninety"}
    keys = []
    for k in word_num.keys():
        keys.append(k)

    if len(num) == 1:
        return(word_num[num[0]])
    elif len(num) == 2:
        c = 0
        for k in keys:
            if k == num[0] + num[1]:
                c += 1
        if c == 1:
            return(word_num[num[0] + num[1]])
        else:
            return(word_num[str(int(num[0]) * 10)] + " " + word_num[num[1]])
    elif len(num) == 3:
        c = 0
        for k in keys:
            if k == num[1] + num[2]:
                c += 1
        if c == 1:
            return(word_num[num[0]]+ " Hundred " + word_num[num[1] + num[2]])
        else:
            return(word_num[num[0]]+ " Hundred " + word_num[str(int(num[1]) * 10)] + " " + word_num[num[2]])
    elif len(num) == 4:
        c = 0
        for k in keys:
            if k == num[2] + num[3]:
                c += 1
        if c == 1:
            if num[1] == '0' :
                return(word_num[num[0]]+ " Thousand " + word_num[num[2] + num[3]])
            else:
                return(word_num[num[0]]+ " Thousand " + word_num[num[1]]+ " Hundred " + word_num[num[2] + num[3]])

        else:
            if num[1] == '0' :
                return(word_num[num[0]]+ " Thousand " + word_num[str(int(num[2]) * 10)] + " " + word_num[num[3]])
            else:
                return(word_num[num[0]]+ " Thousand " + word_num[num[1]]+ " Hundred " + word_num[str(int(num[2]) * 10)] + " " + word_num[num[3]])
    elif len(num) == 5:
        c = 0
        d = 0
        for k in keys:
            if k == num[3] + num[4]:
                c += 1
        for k in keys:
            if k == num[0] + num[1]:
                d += 1
        if d == 1:
            val = word_num[num[0] + num[1]] 
        else:
            val = word_num[str(int(num[0]) * 10)] + " " + word_num[num[1]]

        if c == 1:
            if num[1] == '0' :
                return(val + " Thousand " + word_num[num[3] + num[4]])
            else:
                return(val + " Thousand " + word_num[num[2]]+ " Hundred " + word_num[num[3] + num[4]])

        else:
            if num[1] == '0' :
                return(val + " Thousand " + word_num[str(int(num[3]) * 10)] + " " + word_num[num[4]])
            else:
                return(val + " Thousand " + word_num[num[2]]+ " Hundred " + word_num[str(int(num[3]) * 10)] + " " + word_num[num[4]])


num = [str(d) for d in input("Enter number: ")]
print(num_to_word(num).upper())
于 2020-10-20T17:37:25.490 回答
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 ""

您可以根据约定更改面额,这将适用于您想输入多少大数字

于 2021-06-27T11:10:34.013 回答
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"
于 2021-08-08T00:33:33.833 回答
0

此任务的最佳解决方案是:

 words = "zero one two three four five six seven eight nine" + \
    " ten eleven twelve thirteen fourteen fifteen sixteen seventeen eighteen nineteen twenty" + \
" thirty forty fifty sixty seventy eighty ninety"
words = words.split(" ")

def number2words(n):
    if n < 20:
        return words[n]
    elif n < 100:
        return words[18 + n // 10] + ('' if n % 10 == 0 else '-' + words[n % 10])
    elif n < 1000:
        return number2words(n // 100) + " hundred" + (' ' + number2words(n % 100) if n % 100 > 0 else '')
    elif n < 1000000:
        return number2words(n // 1000) + " thousand" + (' ' + number2words(n % 1000) if n % 1000 > 0 else '')
于 2021-10-28T11:39:57.760 回答
0

如果您来自印度次大陆,他们使用 Lakhs、Crores 等而不是 Million、Billion 等,您可以使用此功能 -

它是递归的,不考虑小数。您可以将您的数字分成两部分并通过连接整数和小数部分来打印。

def Words(n):
    units = ["Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"]
    teens = ["Ten","Eleven","Twelve","Thirteen","Fourteen","Fifteen","Sixteen","Seventeen","Eighteen","Nineteen"]
    tens = ["Twenty","Thirty", "Fourty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"]

    if n <=9:
        return units[n]
    elif n >= 10 and n <= 19:
        return teens[n-10]
    elif n >= 20 and n <= 99:
        return tens[(n//10)-2] + " " + (units[n % 10] if n % 10 !=0 else "")
    elif n >= 100 and n <= 999:
        return Words(n//100) + " Hundred " + (Words(n % 100) if n % 100 !=0 else "")
    elif n >= 1000 and n <= 99999:
        return Words(n//1000) + " Thousand " + (Words(n % 1000) if n % 1000 !=0 else "")
    elif n >= 100000 and n <= 9999999:
        return Words(n//100000) + " Lakh " + (Words(n % 100000) if n % 100000 !=0 else "")
    elif n >= 10000000:
        return Words(n//10000000) + " Crore " + (Words(n % 10000000) if n % 10000000 !=0 else "")

上述函数将生成任意数量的单词!

为了测试这一点,我在 Python 中使用了以下代码 -

from words import Words
import random as r
import time as t

# Forever loop generated random nos 
# and prints in text 
while True:
    rn = r.randrange(0,1000000)
    print("%7d      %s" % (rn, Words(rn)))
    t.sleep(0.25)

上面的程序会生成零到一百万之间的随机数,并每四分之一秒打印一次等效的单词!

于 2022-02-08T20:25:44.130 回答
-1

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

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)
于 2019-04-06T18:18:02.203 回答
-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=" ")
于 2021-08-11T06:23:02.933 回答
-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))
于 2017-07-22T09:43:38.077 回答