0

可能重复:
我如何告诉 Python 将整数转换为单词

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

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

4 回答 4

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

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

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

于 2012-09-24T03:10:01.630 回答
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'
于 2012-09-24T03:16:10.637 回答
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
于 2012-09-24T03:10:23.563 回答
0

这是一个相对紧凑且漂亮的代码版本,可以在一般意义上执行您想要的操作(适用于所有数字,而不仅仅是十二个)。

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
于 2012-09-24T07:16:35.067 回答