gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 06:54:51 25 4
gpt4 key购买 nike

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

关于python - 如何在 python 中将整数转换为单词?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35794173/

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