سؤال

كيف تطبع Pythonistas رقمًا ككلمات ، مثل ما يعادل رمز 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 Core ، ولكن هناك مكتبة الطرف الثالث 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 لا يتم تحويلها إلى عدد صحيح على وجه التحديد ، لا في مثالك)

نصائح أخرى

لقد بدأت للتو عملًا بالتراكمة ، وقد يكون ذلك مفيدًا.

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

يعيد قائمة من الأوتار ، ويأتي مع وظائف اختبار سهلة randomizer() prettizer() والوظيفة الأساسية humanizer()

قد يتعامل مع أعداد كبيرة جدًا لأنه لم يستخدم المقسم ، ولكنه يستخدم تجزئة السلسلة والمعالجة.

يمكنك إدخال رقم أو سلسلة.

بما أنني لم أكتب التحقق من الأرقام ، فإنه يمكنه حتى التعامل مع نص غير رقم :)

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

هنا كوسيلة للقيام بذلك:

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
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top