python:将数字转换为单词

时间:2014-06-08 19:14:02

标签: python

我试图编写一个将数字转换为单词的代码,最多可达999万亿。到目前为止,这是我的代码。它可以达到119,但之后就会变得凌乱。我无法使用追加或枚举。我一直坚持如何打印更大的数字;我如何格式化数字,如978,674,237,105?

NUMBERS = ["zero", "one", "two","three","four","five","six","seven","eight","nine",
               "ten","eleven","twelve","thirteen","fourteen","fiveteen","sixteen",
               "seventeen","eightteen","nineteen"]

TENS = ["", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty",
            "ninety"]

HUNNITS = ["","hundred","thousand","million","billion","trillion"]

n = eval(input("What is the number the you want to convert? "))

def convert():
    if n >= 20:
        tens = n // 10
        units = n % 10

        if units != 0:
            result = TENS[tens] + "-" + NUMBERS[units]
        else:
            result = TENS[tens]
    else:
        result = NUMBERS[n]

    print (result)

def convert2():
    if n >=100:
        tens2 = n//100
        units2 = n%100

        if units2 != 0:
            result2 = HUNNITS[tens2] + "-" + TENS[tens2] + "and" + NUMBERS[units2]
        else:
            result2 = HUNNITS[tens2]
    else:
        result2 = HUNNITS[n]

    print(result2)

def main():
    if n >=20 and n< 100:
        x = convert()
    if n >=100:
        y = convert2()

main()

4 个答案:

答案 0 :(得分:1)

我不想劝阻你,但这个问题已经解决了。有一个简洁的Python模块来执行此操作,称为num2words

以下是link to the GitHub repository

here is the actual script用于英语(它支持多种语言)。如果仍然需要,你可以获得一些灵感来修复你的脚本。

答案 1 :(得分:0)

我使用原始列表并使用python 2为项目euler编写了这个。可能有很多错误我没有对它进行过多的测试,但它应该有助于你们

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'

答案 2 :(得分:0)

这可以很容易地递归完成:

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

答案 3 :(得分:0)

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

这是一个例子:

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