将数字改为单词

时间:2012-09-24 03:05:45

标签: python integer

  

可能重复:
  How do I tell Python to convert integers into words

我正在尝试编写一个简单的函数,它将输入作为整数,然后将其显示为单词。我不确定如何正确地说出这个问题。这是一个时钟应用程序,这就是我正在做的,但我相信有一个更简单的方法。

if h == 1: h = "One"
if h == 2: h = "Two"
if h == 3: h = "Three"
if h == 4: h = "Four"
if h == 5: h = "Five"
if h == 6: h = "Six"
if h == 7: h = "Seven"
if h == 8: h = "Eight"
if h == 9: h = "Nine"
if h == 10: h = "Ten"
if h == 11: h = "Eleven"
if h == 12: h = "Twelve"

有人可以告诉我更简单的方法。

4 个答案:

答案 0 :(得分:5)

hours = ["Twelve", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven"]

for i in range(0, 24):
    print(hours[i % 12])

您可以这样做,或使用字典,其中每小时的“名称”由其代表的数字编制索引。

答案 1 :(得分:3)

使用zip构建字典,并使用数字查找单词:

hour_word = ["One", "Two", "Three", "Four", "Five", "Six", "Seven", 
"Eight", "Nine", "Ten", "Eleven", "Twelve"]
clock_dict = dict(zip(range(1, 13), hour_word))
clock_dict[1]
# 'One'
clock_dict[2]
# 'Two'
clock_dict[12]
# 'Twelve'

答案 2 :(得分:1)

简单的方法,

h = ['zero','one','two','three','four','five','six'][h] # check bounds first

如果您没有零,请将其保留在那里,或将其设为None,它仍然有用。

这种方式更加pythonic。并支持仲裁价值

lst = ['zero','one','two','three','four','five','six']
d = dict(zip(range(len(lst)),lst))
print (d[2]) #prints two

答案 3 :(得分:0)

这是一个相对紧凑和漂亮的代码版本,可以在一般意义上做你想要的(对于所有数字,而不是最多12个)。

level1 = [ "", "one", "two", "three", "four",  "five", "six", "seven", "eight", "nine" ]
level2 = [ "", "eleven", "twelve", "thirteen",  "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen" ]
level3 = [ "", "ten", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety" ]
level4 = [ "","thousand", "million" ]


def number2string(number):
    if number == 0:
        return "zero"
    string = ""
    nparts = (len(str(number)) + 2) / 3
    filled = str(number).zfill(nparts * 3)
    for i in range(nparts):
        d3, d2, d1 = map(int, filled[3*i:3*(i+1)])
        d4 = nparts - i - 1
        string += " "*(i>0)
        string += (d3>0)*(level1[d3] + " hundred" + " "*(d2*d1>0))
        if d2 > 1:
            string += level3[d2] + (" " + level1[d1])*(d1 >= 1)
        elif d2 == 1:
            string += level2[d1]*(d1 >= 1) or level3[d2]
        elif d1 >= 1:
            string += level1[d1]
        string += (" " + level4[d4])*(d4 >= 1 and (d1+d2+d3) > 0)
    return string