繁体   English   中英

如何在 Python 中将数字转换为文本?

[英]How do I turn digits into texts in Python?

如何创建将数字返回文本的 function? 例如,将 33 变成“三三”。

到目前为止我的代码:

table = {
    1: "one",
    2: "two",
    3: "three",
    4: "four",
    5: "five",
    6: "six",
    7: "seven",
    8: "eight",
    9: "nine",
    10: "ten"
}

def digits_to_text(s):
    return table.get(s)

这仅适用于将单个数字转换为文本的情况。

您可以将数字转换为字符串,将其拆分为字符,转换每个字符,然后将它们组合成一个字符串。

table = {
    0: "zero",
    1: "one",
    2: "two",
    3: "three",
    4: "four",
    5: "five",
    6: "six",
    7: "seven",
    8: "eight",
    9: "nine"
}

def digits_to_text(s):
    output = []
    for char in str(s): # convert to string, and loop through each character
        output.append(table.get(int(char))) # convert character to word and add to the list
    return " ".join(output) # join the list together into a single string

另外,您的字典缺少 0 并且有 10,因此我在示例中对其进行了更改。

  1. 将数字类型转换为字符串。
  2. 遍历每个字符
    • 在将其类型转换回 integer 以从字典中获取值时。
 table = { 0: "zero", 1: "one", 2: "two", 3: "three", 4: "four", 5: "five", 6: "six", 7: "seven", 8: "eight", 9: "nine" } def digits_to_text(s): return " ".join([table.get(int(i)) for i in str(s)])

查看问题的字母,似乎用户不需要 map 0到任何东西,除非前面有1 ,在这种情况下它将映射到ten 我不知道这是对问题的错误描述还是真正的需要。 在第一种情况下,上述解决方案很好地解决了目标。 否则,我们可以采取以下方法:

table = {
    1: "one",
    2: "two",
    3: "three",
    4: "four",
    5: "five",
    6: "six",
    7: "seven",
    8: "eight",
    9: "nine",
    10: "ten"
}

def digits_to_letters(s, default= "-"):
    s = list(s)[::-1]
    res = []
    while len(s) > 0:
        l1 = s.pop()
        n1 = int(l1)
        c1 = table.get(n1, " ")
        if (n1 == 1) and (len(s) > 0):
            l2 = s.pop()
            n1n2 = int(l1 + l2)
            c1c2 = table.get(n1n2)
            if c1c2:
                res.append(c1c2)
            else:
                res.append(c1)
                res.append(table.get(int(l2), default))
        else:
            res.append(c1)
    return res
            
print(digits_to_letters("123102303231"))

OUTPUT

['one', 'two', 'three', 'ten', 'two', 'three', ' ', 'three', 'two', 'three', 'one']

如您所见,第四和第五个字符 - 10 - 映射到ten ,而第七和第八个 - 30 - 映射到three (可以选择不同的默认字符而不是空格)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM