python: converting numbers to words

后端 未结 4 604
无人共我
无人共我 2021-01-13 23:08

I\'m trying to write a code that will convert numbers to words, up to 999 trillion. here is my code so far. it works up to 119, but after that things get messy. I can\'t use

相关标签:
4条回答
  • 2021-01-13 23:36

    This can easily be done recursively:

    def as_words(n):
        """Convert an integer n (+ve or -ve) to English words."""
        # lookups
        ones = ['zero', 'one', 'two', 'three', 'four',
                'five', 'six', 'seven', 'eight', 'nine', 
                'ten', 'eleven', 'twelve', 'thirteen', 'fourteen',
                'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen']
        tens = ['zero', 'ten', 'twenty', 'thirty', 'forty',
                'fifty', 'sixty', 'seventy', 'eighty', 'ninety']
        # negative case
        if n < 0:
            return "minus {0}".format(as_words(abs(n)))
        # 1000+
        for order, word in [(10**12, "trillion"), (10**9, "billion"),
                            (10**6, "million"), (10**3, "thousand")]:
            if n >= order:
                return "{0} {1}{2}".format(as_words(n // order), word,
                                           " {0}".format(as_words(n % order))
                                           if n % order else "")
        # 100-999
        if n >= 100:
            if n % 100:
                return "{0} hundred and {1}".format(as_words(n // 100), 
                                                    as_words(n % 100))
            else:
                return "{0} hundred".format(as_words(n // 100))
        # 0-99
        if n < 20:
            return ones[n]
        else:
            return "{0}{1}".format(tens[n // 10],
                                   "-{0}".format(as_words(n % 10)) 
                                   if n % 10 else "")   
    
    0 讨论(0)
  • 2021-01-13 23:41

    I don't want to discourage you, but this problem has already been solved. There is a neat Python module to do this, called num2words

    Here is the link to the GitHub repository

    And here is the actual script for the English language (it supports multiple languages). There you can get some inspiration to fix your script if still needed.

    0 讨论(0)
  • 2021-01-13 23:50

    I wrote this for project euler using lists originally and using python 2 . There may well be bugs I have not tested it too much but it should hopefully help you along

    nums = ["", "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"]
    def num_to_words():
        n= int(input("Enter number to convert: "))
        words = ""
        if n == 0:
            words += "zero"
        else:
            numStr = "%d" % n
            groups = (len(numStr) + 2) // 3
            numStr = numStr.zfill(groups * 3)
            for i in range(0, groups*3, 3):
                h = int(numStr[i])
                t = int(numStr[i+1])
                u = int(numStr[i+2])
                g = groups - (i // 3 + 1)
                if h >= 1:
                    words += nums[h]
                    words +=  " hundred "
                    words+=" "
                    if int(numStr) % 100:   # if number  modulo 100 has remainder  add "and" i.e one hundred and ten
                        words+=" and "
                if t > 1:
                    words+= tens[t]
                    if u >= 1:
                        words+= nums[u]
                        words+=" "
                elif t == 1:
                    if u >= 1:
                        words+= teens[(u)]
                    else:
                        words+= tens[t]
                        words+=" "
                else:
                    if u >= 1:
                        words+= nums[u]
                        words+=" "
    
                if g >= 1 and (h + t + u) > 0:
                    words+= thousands[g]
                    words+=" "
        return words
    In [7]: num_to_words()
    Enter number to convert: 12399990
    Out[7]: 'twelvemillion three hundred   and ninetynine  thousand nine  hundred   and ninety'
    
    0 讨论(0)
  • 2021-01-13 23:57

    This worked for me in Python 3.x:

    print('Type any number here: ')
    number = input()
    int_side = number
    dec_side = ''
    for i in range(0, len(number)):
        if number[i] == '.':
            int_side = number[:i]
            dec_side = number[i + 1:]
            break
    while not (int_side.isdigit()) or not (dec_side.isdigit()) and dec_side != '':
        dec_side = ''
        print('Only numbers are allowed! (decimals included, but not fractions)')
        print('Type any number here: ')
        number = input()
        int_side = number
        for i in range(0, len(number)):
            if number[i] == '.':
                int_side = number[:i]
                dec_side = number[i + 1:]
        user_choice = input()
    int_length = len(int_side)
    ones = ['', 'one ', 'two ', 'three ', 'four ', 'five ', 'six ', 'seven ', 'eight ', 'nine ']
    teens = ['ten ', 'eleven ', 'twelve ', 'thirteen ', 'fourteen ', 'fifteen ', 'sixteen ', 'seventeen ', 'eighteen ',
             'nineteen ']
    decades = ['', '', 'twenty ', 'thirty ', 'forty ', 'fifty ', 'sixty ', 'seventy ', 'eighty ', 'ninety ']
    hundreds = ['', 'one hundred ', 'two hundred ', 'three hundred ', 'four hundred ', 'five hundred ', 'six hundred ',
                'seven hundred ', 'eight hundred ', 'nine hundred ']
    comma = ['thousand, ', 'million, ', 'trillion, ', 'quadrillion, ']
    word = ''
    int_length = len(int_side)
    dec_length = len(dec_side)
    change = int_length
    up_change = 0
    while change > 0:
        if int_side == '':
            break
        if number == '0':
            word = 'zero'
            break
        elif change > 1 and int_side[change - 2] == '1':
            for i in range(0, 10):
                if int_side[change - 1] == str(i):
                    word = teens[i] + word
        else:
            if change > 0:
                for i in range(0, 10):
                    if int_side[change - 1] == str(i):
                        word = ones[i] + word
            if change > 1:
                for i in range(0, 10):
                    if int_side[change - 2] == str(i):
                        word = decades[i] + word
        if change > 2:
            for i in range(0, 10):
                if int_side[change - 3] == str(i):
                    word = hundreds[i] + word
        if change > 3:
            word = comma[up_change] + word
        change -= 3
        up_change += 1
    word += 'point '
    for i in range(0, len(dec_side)):
        for x in range(0, 10):
            if dec_side[i] == str(x):
                word += ones[x]
    print(word)
    

    This is an example:

    Type any number here: 13243214.1324hk
    Only numbers are allowed! (decimals included, but not fractions)
    Type any number here: 13243214.1324
    thirteen million, two hundred forty three thousand, two hundred 
    fourteen point one three two four
    
    0 讨论(0)
提交回复
热议问题