在Python中用verbally格式化数字

Way*_*ner 8 python formatting nlp language-comparisons

pythonistas如何将数字作为单词打印,就像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
Run Code Online (Sandbox Code Playgroud)

myk*_*hal 8

没有在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'
Run Code Online (Sandbox Code Playgroud)

(请注意,1e25未精确转换为整数,在您的示例中均未转换为整数)

  • 一点都不奇怪.`1e25`是"使浮点值最接近10 ^ 25",而"1*10**25"表示"乘以10乘以10的结果为25倍".固定宽度浮点运算(在计算机上)在数学上不精确,而最近版本的Python中的整数是任意精度的. (2认同)
  • 1e25不是"指数表达式",它是一个浮点字面值.并且python中的浮点数不能完全代表10**25(考虑到2**84> 10**25> 2**83,这不应该是一个很大的惊喜). (2认同)