在Python中以口头格式化数字

9 投票
3 回答
3658 浏览
提问于 2025-04-16 00:40

怎么让Python程序员把数字打印成文字,比如和下面的Common Lisp代码效果一样:

[3]> (format t "~r" 1e25)
nine septillion, nine hundred and ninety-nine sextillion, nine hundred and ninety-nine quintillion, seven hundred and seventy-eight quadrillion, one hundred and ninety-six trillion, three hundred and eight billion, three hundred and sixty-one million, two hundred and sixteen thousand

3 个回答

0

这里有一种方法可以做到:

def abbreviate(x):
    abbreviations = ["", "K", "M", "B", "T", "Qd", "Qn", "Sx", "Sp", "O", "N", 
    "De", "Ud", "DD"]
    thing = "1"
    a = 0
    while len(thing) < len(str(x)) - 3:
        thing += "000"
        a += 1
    b = int(thing)
    thing = round(x / b, 2)
    return str(thing) + " " + abbreviations[a]

它的作用是:

>>> abbreviate(11423)
11.43 K
1

我刚开始在土耳其做一个项目,这可能会对你有帮助。

https://github.com/guneysus/humanizer-tr

这个项目会返回一个字符串的列表,并且提供了一些简单的测试功能,比如 randomizer()prettizer() 和核心功能 humanizer()

它可以处理非常大的数字,因为它没有用除法的方法,而是通过字符串的分割和操作来实现。

你可以输入数字或者字符串。

由于我没有写数字验证,它甚至可以处理非数字的文本哦 :)

>>> humanizer('STACK OVER FLOW')
['STA Trilyon', 'CK  Milyar', 'OVE Milyon', 'R F Bin', 'LOW']
9

在Python的核心功能里没有这个,但有一个第三方库叫做 num2words

>>> from num2words import num2words
>>> num2words(1e25)
'ten septillion, one billion, seventy-three million, seven hundred and forty-one thousand, eight hundred and twenty-four'

>>> num2words(10000000000000000000000000)
'ten septillion'

(注意,1e25这个数字在你的例子中也没有被准确地转换成整数)

撰写回答