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

标签 python python-2.7

我想将数字转换成文字。我准备了以下代码,但出了点问题。我刚开始使用 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/

相关文章:

python - 如何在 Windows 操作系统中升级/卸载 distutils 软件包 (PyYAML)

python - Scrapy - TypeError : Cannot convert unicode body - HtmlResponse has no encoding

python - 使用多处理不会减少计算时间

python - 在Python中将嵌套数组转换为pandas数据框

python - 比较两个列表并只打印差异? (异或两个列表)

python - 如何在 Google Colaboratory 中使用 IBM python 模块 "pixiedust"?

python - GAE users.get_current_user() 返回 None

python - 在 Python 中使随机模块线程安全

python - 如何阻止 apply() 改变列的顺序?

python - Tensorflow 无法在评估过程中恢复词汇