gpt4 book ai didi

python:将数字转换为单词

转载 作者:行者123 更新时间:2023-11-28 18:42:57 26 4
gpt4 key购买 nike

我正在尝试编写一个代码,将数字转换为最多 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()

最佳答案

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

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

关于python:将数字转换为单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24109866/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com