我想写一段代码将输入数字转换成单词。例如,如果我输入420,则将输出四二零。到目前为止,我有字典和将输入转换为单独字符的方法。但是,我不知道如何将两者结合起来并打印输出。 print(temp)不起作用。谢谢。我不能使用num2words。
def convert( number ):
str(word)=number
[int(word)for word in str(number)]
dict = {
"0": "Zero ",
"1": "One ",
"2": "Two ",
"3": "Three ",
"4": "Four ",
"5": "Five ",
"6": "Six ",
"7": "Seven ",
"8": "Eight ",
"9": "Nine "
}
print(word)
答案 0 :(得分:2)
不确定在这里是否需要功能。您可以尝试如下操作:
mydict = {"0": "Zero ",
"1": "One ",
"2": "Two ",
"3": "Three ",
"4": "Four ",
"5": "Five ",
"6": "Six ",
"7": "Seven ",
"8": "Eight ",
"9": "Nine "
}
num = 420
# for each letter in string value of number
for ch in str(num):
# get the letter from dictionary and print the word
print(mydict[ch], end=' ')
或在list comprehension
中使用一行:
print(*[mydict[ch] for ch in str(num)])
答案 1 :(得分:1)
只需像这样更改您的功能:
def convert( number ):
word = ""
dict = {
"0": "Zero ",
"1": "One ",
"2": "Two ",
"3": "Three ",
"4": "Four ",
"5": "Five ",
"6": "Six ",
"7": "Seven ",
"8": "Eight ",
"9": "Nine "
}
for i in str(number):
word += dict[i]
return word
convert(532)
# 'Five Three Two '
答案 2 :(得分:0)
您可以将代码更改为:
def Prob0( num ):
for temp in str(num):
dict = {
"0": "Zero ",
"1": "One ",
"2": "Two ",
"3": "Three ",
"4": "Four ",
"5": "Five ",
"6": "Six ",
"7": "Seven ",
"8": "Eight ",
"9": "Nine "
}
print(dict[temp])
Prob0(420)