问题
How do pythonistas print a number as words, like the equivalent of the Common Lisp code:
[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
回答1:
no in python core, but there is 3rd party library 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'
(note that 1e25 is not converted to integer precisely, neither in your example)
回答2:
I just started a work in Turkish, it may be helpful.
https://github.com/guneysus/humanizer-tr
It return a list of strings, and comes with easy testing functions randomizer()
prettizer()
and the core function humanizer()
It may handle very large numbers because it did not use dividing approach, but uses string segmentation and manipulation.
You can enter even number or string.
Since i did not write a number verification it can even handle a non number text :)
>>> humanizer('STACK OVER FLOW')
['STA Trilyon', 'CK Milyar', 'OVE Milyon', 'R F Bin', 'LOW']
回答3:
Here as a way to do it:
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]
It does this:
>>> abbreviate(11423)
11.43 K
来源:https://stackoverflow.com/questions/3158132/verbally-format-a-number-in-python