gpt4 book ai didi

python - 我想输入任意长度的数字,然后我想将其转换为单词形式。例如,如果我输入 615,它应该打印 ' six one five'

转载 作者:行者123 更新时间:2023-11-28 20:14:40 24 4
gpt4 key购买 nike

diction = {
0 : "zero",
1 : "one",
2 : "two",
3 : "three",
4 : "four",
5 : "five",
6 : "six",
7 : "seven",
8 : "eight",
9 : "nine",
}
n = int(input("Input a number: "))
print (diction[n])

这是我的代码,但只有当我输入一个数字时它才有效。输入多于 1 位时返回错误。我该如何解决?

最佳答案

您需要遍历输入的数字,一次一个数字,然后在您的字典中查找:

diction = {
0 : "zero",
1 : "one",
2 : "two",
3 : "three",
4 : "four",
5 : "five",
6 : "six",
7 : "seven",
8 : "eight",
9 : "nine",
}
n = int(input("Input a number: "))
print (' '.join(diction[int(x)] for x in str(n)))

请注意,由于您必须遍历一个字符串,然后将其转换回 int 以在字典中查找,因此将字典中的键存储为字符串可能更容易。

编辑:如果您想获得数字的完整英文名称,例如465465,您可能需要查看 inflect包。

关于python - 我想输入任意长度的数字,然后我想将其转换为单词形式。例如,如果我输入 615,它应该打印 ' six one five',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48902439/

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