gpt4 book ai didi

python - 如何将数字转换成文字

转载 作者:太空宇宙 更新时间:2023-11-04 10:28:07 27 4
gpt4 key购买 nike

我想将数字转换成文字。我准备了以下代码,但出了点问题。我刚开始使用 python。

number="22"
new_dict={0:'zero',1:'one',2:'two',3:'three',4:'four',5:'five',6:'six',7:'seven',8:'eight',9:'nine'}
for x in number:
if x in new_dict.values():
print new_dict[x]

在这种情况下,我没有收到任何输出。有人可以帮忙吗,我的代码有什么问题?

最佳答案

将键存储为字符串并检查数字中的每个数字是否是字典/键而不是值:

number="22"
new_dict={"0":'zero',"1":'one',"2":'two',"3":'three',"4":'four',"5":'five',"6":'six',"7":'seven',"8":'eight',"9":'nine'}
for x in number:
if x in new_dict:
print(new_dict[x])
two
two

或者使用 str.join:

print('\n'.join([new_dict[n] for n in number if n in new_dict]))

您的代码失败,因为 2"2" 不同,并且您正在检查值而不是 number< 中每个数字/字符的键

这是我用于将数字转换为单词的编码挑战的一些非常古老的代码:

nums = ["", "one", "two", "three", "four",  "five",
"six", "seven", "eight", "nine "]
teens = ["", "eleven", "twelve", "thirteen", "fourteen",
"fifteen", "sixteen", "seventeen", "eighteen", "nineteen"]
tens = ["", "ten", "twenty", "thirty", "forty",
"fifty", "sixty", "seventy", "eighty", "ninety"]
thousands = ["","thousand", "million", "billion", "trillion"]

def num_to_words():
n= int(input("Enter number to convert: "))
words = ""
if n == 0:
words += "zero"
else:
numStr = "%d" % n
groups = (len(numStr) + 2) // 3
numStr = numStr.zfill(groups * 3)
for i in range(0, groups*3, 3):
h = int(numStr[i])
t = int(numStr[i+1])
u = int(numStr[i+2])
g = groups - (i // 3 + 1)
if h >= 1:
words += nums[h]
words += " hundred "
words+=" "
if int(numStr) % 100: # if number modulo 100 has remainder add "and" i.e one hundred and ten
words+=" and "
if t > 1:
words+= tens[t]
if u >= 1:
words+= nums[u]
words+=" "
elif t == 1:
if u >= 1:
words+= teens[(u)]
else:
words+= tens[t]
words+=" "
else:
if u >= 1:
words+= nums[u]
words+=" "

if g >= 1 and (h + t + u) > 0:
words+= thousands[g]
words+=" "
return words

关于python - 如何将数字转换成文字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28266307/

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