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)
我的问题是,如何分离数字然后与我创建的字典进行比较?我知道长度不适用于整数数据类型。我知道进一步的逻辑是将键发送到字典并获取它们各自的值。但在此之前,我被困在这里分隔整数的数字。
请您参考如下方法:
为其使用模块: https://pypi.python.org/pypi/num2words
另外,检查类似的问题:How do I tell Python to convert integers into words
您可以安装模块并查看它是如何在那里实现的。
但是你的问题是这样解决的:
def numbers_to_words (number):
number2word = {'1': "one", '2': "two", '3': "three", '4': "four", '5': "five", '6': "six",
'7': "seven", '8': "eight", '9': "nine", '0': "zero"}
return " ".join(map(lambda i: number2word[i], str(number)))
print(numbers_to_words(1234))
