用python人性化数字

时间:2015-05-20 00:44:40

标签: python

我正在使用humanize库来生成一些人类阅读数字。 这适用于数百万人。

humanize.intword(123455913) # 123.5 million

我的问题是成千上万。

humanize.intword(1000) # I am expecting something like 1k, but the output is 1000

基本上,人性化只适用于数百万人。对此有何想法?另一个库或纯python实现?

3 个答案:

答案 0 :(得分:5)

此库似乎不支持您的特定用例,但您可以通过编辑numbers.py第54和55行来添加功能:

powers = [10 ** x for x in (3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 100)]
human_powers = (N_('thousand'), N_('million'), N_('billion'), N_('trillion'), N_('quadrillion'),
                N_('quintillion'), N_('sextillion'), N_('septillion'),
                N_('octillion'), N_('nonillion'), N_('decillion'), N_('googol'))

答案 1 :(得分:3)

这为我完成了这项工作:

def humanize_number(value, fraction_point=1):
    powers = [10 ** x for x in (12, 9, 6, 3, 0)]
    human_powers = ('T', 'B', 'M', 'K', '')
    is_negative = False
    if not isinstance(value, float):
        value = float(value)
    if value < 0:
        is_negative = True
        value = abs(value)
    for i, p in enumerate(powers):
        if value >= p:
            return_value = str(round(value / (p / (10.0 ** fraction_point))) /
                               (10 ** fraction_point)) + human_powers[i]
            break
    if is_negative:
        return_value = "-" + return_value

    return return_value

答案 2 :(得分:0)

改编Yonatan的答案,打印出一定数量的有效数字

def humanize_number(value, significant_digits=3, strip_trailing_zeros=True):
    """
    Adaption of humanize_numbers_fp that will try to print a given number of significant digits, but sometimes more or
    less for easier reading.

    Examples:
    humanize_number(6666666, 2) = 6.7M
    humanize_number(6000000, 2) = 6M
    humanize_number(6000000, 2, strip_trailing_zeros=False) = 6.0M
    humanize_number(.666666, 2) = 0.67
    humanize_number(.0006666, 2) = 670µ
    """
    powers = [10 ** x for x in (12, 9, 6, 3, 0, -3, -6, -9)]
    human_powers = ['T', 'B', 'M', 'K', '', 'm', u'µ', 'n']
    is_negative = False
    suffix = ''

    if not isinstance(value, float):
        value = float(value)
    if value < 0:
        is_negative = True
        value = abs(value)
    if value == 0:
        decimal_places = max(0, significant_digits - 1)
    elif .001 <= value < 1:  # don't humanize these, because 3.0m can be interpreted as 3 million
        decimal_places = max(0, significant_digits - int(floor(log10(value))) - 1)
    else:
        p = next((x for x in powers if value >= x), 10 ** -9)
        i = powers.index(p)
        value = value / p
        before = int(log10(value)) + 1
        decimal_places = max(0, significant_digits - before)
        suffix = human_powers[i]

    return_value = ("%." + str(decimal_places) + "f") % value
    if is_negative:
        return_value = "-" + return_value
    if strip_trailing_zeros and '.' in return_value:
        return_value = return_value.rstrip('0').rstrip('.')

    return return_value + suffix