在python中如何将整数转换为单词?

2024-06-12 18:37:09 发布

您现在位置:Python中文网/ 问答频道 /正文

Write a function that takes an integer as input argument and returns the integer using words. For example if the input is 4721 then the function should return the string "four seven two one". Note that there should be only one space between the words and they should be all lowercased in the string that you return.

这是我的代码:

def Numbers_To_Words (number):
    dict = {1: "one", 2: "two", 3: "three", 4: "four", 5: "five", 6: "six", 7: "seven", 8: "eight", 9: "nine", 0: "zero"}
    output_str = " "
    list = []

#Main Program
number = 4721
result = Numbers_To_Words (number)
print (result)

我的问题是,如何将数字分开,然后与我创建的词典进行比较?我知道长度不适用于整数数据类型。我知道更进一步的逻辑是将键发送到字典并获得它们各自的值。但在此之前,我被困在整数的分隔数字上。在


Tags: andthenumberinputstringreturnthatfunction
3条回答

有一种方法比其他方法更简单:

def number_to_words(number)
    words = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten"]
    return " ".join(words[int(i)] for i in str(number))

使用模块: https://pypi.python.org/pypi/num2words

同样,检查类似的问题:How do I tell Python to convert integers into words

你可以安装这些模块,看看它是如何实现的。在

但你的问题解决的方式是:

def Numbers_To_Words (number):
    dictionary = {'1': "one", '2': "two", '3': "three", '4': "four", '5': "five", '6': "six",
            '7': "seven", '8': "eight", '9': "nine", '0': "zero"}
    return " ".join(map(lambda x: dictionary[x], str(number)))


print Numbers_To_Words(1234)
def number_to_words(number):
    dict={"1":"one","2":"two","3":"three","4":"four","5":"five","6":"six","7":"seven","8":"eight","9":"nine","0":"zero"}
    s=""
    for c in str(number):
        s+=dict[c]+" "
    #if it's matter that the string won't conatain
    #space at the end then add the next line:
    s=s[:-1]

    return s

相关问题 更多 >