【问题标题】:Verbally format a number in Python在 Python 中口头格式化数字
【发布时间】:2011-03-10 15:28:01
【问题描述】:

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

【问题讨论】:

    标签: python formatting nlp language-comparisons


    【解决方案1】:

    在python核心中没有,但是有第3方库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 并未精确转换为整数)

    【讨论】:

    • 非常好 - 我实际上注意到了这一点,但它是 python (C?) 如何处理指数表达式的错误:int(1e25) 产生 10000000000000000905969664L1*10**25 产生 10000000000000000000000000L。奇怪吗?
    • 一点也不奇怪。 1e25 是“使浮点值最接近 10^25”,1*10**25 表示“将 10 与自身相乘 25 次的结果乘以 1”。固定宽度的浮点运算(在计算机上)在数学上并不精确,而最新版本的 Python 中的整数是任意精度的。
    • 1e25 不是“指数表达式”,而是浮点文字。并且 python 中的浮点数不能完全表示 1025(考虑到 284 > 1025 > 283,这不应该是一个很大的惊喜)。
    • 有趣且内容丰富!根据这些信息,我很好奇并玩了一会儿,如果你想要准确,你可以import decimal; d = decimal.Decimal('1e25'),你不会得到浮点错误。
    【解决方案2】:

    我刚开始用土耳其语工作,可能会有所帮助。

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

    它返回一个字符串列表,并带有简单的测试函数randomizer()prettizer()和核心函数humanizer()

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

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

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

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

    【讨论】:

      【解决方案3】:

      这里是一种方法:

      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
      

      【讨论】:

      • 这不回答问题,问题已经接近九年了!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多