如何将数字转换为单词

时间:2015-02-01 18:37:09

标签: 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]

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

2 个答案:

答案 0 :(得分:4)

将密钥存储为字符串并检查数字中的每个数字是否为dict / keys而不是值:

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

答案 1 :(得分:0)

嘿,嘿嘿:

class Number:
    ones = [
        "",         "one",      "two",          "three",        "four",
        "five",     "six",      "seven",        "eight",        "nine",
        "ten",      "eleven",   "twelve",       "thirteen",     "fourteen",
        "fifteen",  "sixteen",  "seventeen",    "eighteen",     "nineteen"
    ]

    tens = [
        "",         "",         "twenty",       "thirty",       "forty",
        "fifty",    "sixty",    "seventy",      "eighty",       "ninety"
    ]

    powers = [
        "",
        "thousand",
        "million",
        "billion",
        "trillion",
        "quadrillion",
        "quintillion",
        "sextillion",
        "septillion",
        "octillion",
        "nonillion",
        "decillion"
        # sufficent to represent any natural number < 10**36
    ]

    max_ = 1000 ** len(powers)

    def __init__(self, n=0):
        self.n = int(n)

    @classmethod
    def _chunk_words(cls, n):
        """
        Return a string for 0 <= n < 1000
        """
        assert 0 <= n < 1000

        # get hundreds, tens, ones
        c, xi = divmod(n, 100)
        x, i  = divmod(xi, 10)

        # get hundreds string
        if c:
            sc = cls.ones[c] + " hundred"
        else:
            sc = ""

        # get tens string and ones string
        if x < 2:
            sx, si = "", cls.ones[10*x + i]
        else:
            sx, si = cls.tens[x], cls.ones[i]

        # get tens-and-ones string
        if sx and si:
            sxi = sx + " " + si
        else:
            sxi = sx or si

        # get hundreds-and-tens-and-ones string
        if sc and sxi:
            scxi = sc + " and " + sxi
        else:
            scxi = sc or sxi

        return scxi

    def __str__(self):
        """
        Return a string representing the number, ie
          `str(Number(342))`  =>  `"three hundred and forty two"`
        """
        n = self.n
        assert 0 <= n < self.max_, "{} is too large (max is {})".format(n, self.max_ - 1)
        if n:
            # break number into thousands-powers
            chunks = []
            while n:
                n, mod = divmod(n, 1000)
                chunks.append(mod)
            # combine with powers and reorder; drop 0-powers
            chunks = [
                (self._chunk_words(ch), pw)
                for ch,pw in zip(chunks, self.powers)
                if ch
            ][::-1]
            return " ".join(ch + " " + pw if pw else ch for ch,pw in chunks)
        else:
            return "zero"

然后

>>> print(Number(22))
twenty two

>>> print(Number(7598312948732))
seven trillion five hundred and ninety eight billion three hundred and twelve million nine hundred and forty eight thousand seven hundred and thirty two