Python 简明教程

Python - Humanize Package

Python 中的 Humanize Package 是一个库,专门设计用于将数字、日期、时间和文件大小转换为更易于人类理解的格式。

The Humanize Package in Python is a library which is specifically designed to convert numerical values, dates, times and file sizes into formats that are more easily understood by humans.

  1. This package is essential for creating user-friendly interfaces and readable reports where data interpretation needs to be quick and intuitive.

  2. The primary goal of the Humanize Package is to bridge the gap between raw data and human understanding.

尽管计算机和数据库擅长处理原始数字数据,但这些格式对于人类来说可能难以快速理解。 Humanize Package 通过将这些数据点转换为更直观、更用户友好的格式来解决这个问题。

Although computers and databases excel at processing raw numerical data but these formats can be challenging for humans to quickly grasp. The Humanize Package tackles this issue by converting these data points into more intuitive and user-friendly formats.

Installation of Humanize Package

要在 Python 中安装 humanize 程序包,我们可以使用 pip,这是 Python 的标准包管理器。必须在命令行或终端中运行以下代码才能安装 Humanize 程序包:

To install the humanize package in Python we can use pip which is the standard package manager for Python. Following code has to be run in the command line or terminal to install Humanize Package −

pip install humanize

安装后,我们可以通过运行 Python 解释器并使用以下代码导入 Humanize 程序包来验证 humanize 是否已正确安装:

After installation we can verify if humanize is installed correctly by running a Python interpreter and importing the Humanize package by using the below code −

import humanize

Different Utilities in Humanize Package

Python 中的 Humanize package 提供了各种实用工具,可将数据转换为人类可读格式,从而增强了可用性和理解。让我们详细探讨 humanize 程序包提供的不同实用工具:

The Humanize package in Python provides a wide range of utilities that transform data into human-readable formats by enhancing usability and comprehension. Let’s explore the different utilities offered by humanize package in detail −

Number Utilities

Python 中的 Humanize 程序包提供了很多实用工具,可以增强数字数据的可读性和理解度。这些实用工具将数字转换为更自然、更易于人类理解的格式。

The Humanize package in Python provides several number of utilities that enhance the readability and comprehension of numerical data. These utilities convert numbers into formats that are more natural and understandable for humans.

Integer Formatting

整数格式化实用程序将大型整数转换为带有逗号的字符串以提高可读性。以下是使用整数格式化实用程序的示例:

The Integer Formatting utility converts large integers into strings with commas for improved readability. Following is the example of applying the integer formatting utility −

import humanize
print(humanize.intcomma(123456))

Output

123,456

Integer Word Representation

整数单词表示将大型整数转换为它们的单词表示以方便理解,特别是对于非常大的数字。以下是它的示例:

The Integer Word Representation converts large integers into their word representation for easier understanding, especially for very large numbers. Below is the example of it −

import humanize
print(humanize.intword(12345678908545944))

Output

12.3 quadrillion

Ordinal Numbers

序数将整数转换为它们的序数形式。例如 1 将表示为 1,2 将表示为 2。以下是将 3 转换为 3 的示例:

The Ordinal numbers converts integers into their ordinal form. For example 1 will be given as 1st and 2 as 2nd. Below is the example converting 3 as 3rd −

import humanize
print(humanize.ordinal(3))

Output

3rd

AP Numbers

这些将整数转换为它们相应的单词。以下是它的示例:

These converts the integers into their corresponding words. Here is the example of it −

import humanize
print(humanize.apnumber(9))

Output

nine

Fractional Units

这将小数转换为分数以获得更直观的表示。以下是它的示例:

This converts decimal numbers into fractions for more intuitive representation. Following is the example of it −

import humanize
print(humanize.fractional(0.5))

Output

1/2

File Size Utilities

我们已经知道 Python 中的人性化包提供了几种实用程序,其中 File Size Utilities 是特别设计用于将原始字节值转换为人类可读文件大小的一种程序。

As we already know that the humanize package in Python provides several utilities among them File Size Utilities is one which is specifically designed to convert raw byte values into human-readable file sizes.

这些实用程序通过将文件大小转换为更容易读取和解释的格式,帮助使文件大小更容易理解。以下是 Python 人性化包中提供的文件大小实用程序的详细概述:

These utilities help to make file sizes more understandable by converting them into formats that are easier to read and interpret. Here is a detailed overview of the file size utilities available in the humanize package −

File Size Formatting using naturalsize()

naturalsize() 函数是将文件大小转换为人类可读格式的主要实用程序。它根据提供的尺寸自动选择适当的单位,例如字节、KB、MB、GB。

The naturalsize() function is the primary utility for converting file sizes into human-readable formats. It automatically selects the appropriate units such as bytes, KB, MB, GB based on the size provided.

Syntax

Syntax

以下是 Python 人性化包文件大小实用程序的 naturalsize() 函数的语法:

Following is the syntax of the naturalsize() function of the File Size Utilities of Python Humanize package −

humanize.naturalsize(value,binary,gnu,format)

Parameter

Parameter

以下是 python 人性化包的 naturalsize() 函数的参数:

Below are the parameters of the naturalsize() function of the python humanize package −

  1. value: The file size in bytes.

  2. binary: A boolean flag to indicate whether to use binary units. The default value is False.

  3. gnu: A boolean flag to indicate whether to use GNU-style output and the default value is False.

  4. format: A string to specify the output format. The default value is "%.1f".

Example

以下是 python 中使用人性化包的 naturalsize() 的示例:

Following is the example of using the naturalsize() of humanize package in python −

import humanize

# Default usage with decimal units
file_size = 123456789
print(f"File size: {humanize.naturalsize(file_size)}")

# Using binary units
print(f"File size (binary): {humanize.naturalsize(file_size, binary=True)}")

# Using GNU-style prefixes
print(f"File size (GNU): {humanize.naturalsize(file_size, gnu=True)}")

# Custom format
print(f"File size (custom format): {humanize.naturalsize(file_size, format='%.2f')}")

输出如下:

Following is the output −

File size: 123.5 MB
File size (binary): 117.7 MiB
File size (GNU): 117.7M
File size (custom format): 123.46 MB

Date Time Utilities

Humanize package 在 Python 中提供了几个实用程序,以使日期和时间更具可读性。这些实用程序将日期-时间对象转换为更容易让人理解的格式,例如相对时间、自然日期等等。以下是人性化包提供的日期和时间实用程序的详细概述:

The Humanize package in Python provides several utilities for making dates and times more readable. These utilities transform date-time objects into formats that are easier for humans to understand such as relative times, natural dates and more. Following is the detailed overview of the date and time utilities offered by the humanize package −

Natural Time

Natural Time 将日期-时间对象转换为人类可读的相对时间,例如 2 天前,3 小时前。以下是自然时间示例:

The Natural Time converts date-time objects into human-readable relative times such as 2 days ago, 3 hours ago. Following is the example of natural time −

import humanize
from datetime import datetime, timedelta

past_date = datetime.now() - timedelta(days=2)
print(humanize.naturaltime(past_date))

Output

2 days ago

Natural Date

Natural Date 将特定日期格式化为可读格式,例如“2024 年 7 月 11 日”。这是示例:

The Natural Date formats specific dates into a readable format like "July 11, 2024". Here is the example −

import humanize
from datetime import datetime
some_date = datetime(2022, 7, 8)
print(humanize.naturaldate(some_date))

Output

Jul 08 2022

Natural Day

Natural Day 考虑今天的日期以进行上下文相关性,比如“今天”、“明天”、“昨天”等,提供日期的人类可读表示形式。以下是其示例 −

The Natural Day provides a human-readable representation of a date by considering today’s date for contextual relevance, for example "today", "tomorrow", "yesterday" etc. Below is the example of it −

import humanize
from datetime import datetime, timedelta
today = datetime.now()
tomorrow = today + timedelta(days=1)
print(humanize.naturalday(today))
print(humanize.naturalday(tomorrow))

Output

today
tomorrow

Precise Delta

Precise Delta 通过细分为天、小时、分钟和秒,将持续时间转换为人类可读字符串。以下是其示例 −

The Precise Delta converts time duration into human-readable strings by breaking down into days, hours, minutes and second. Here is the example of it −

import humanize
from datetime import timedelta
duration = timedelta(days=2, hours=3, minutes=30)
print(humanize.precisedelta(duration))

Output

2 days, 3 hours and 30 minutes

Duration Utilities

Python 中的 humanize 包还包括 Duration Utilities ,用于将持续时间(时间间隔)转换为人类可读格式。这些实用工具有助于以用户可理解且有意义的方式显示持续时间。以下是 humanize 包提供的持续时间实用工具的概述 −

The humanize package in Python also includes the Duration Utilities for converting duration (time intervals) into human-readable formats. These utilities help to present duration in a way that is understandable and meaningful to users. Here’s an overview of the duration utilities provided by humanize package −

Duration Formatting using naturaldelta()

naturaldelta() 函数将时间差(持续时间)转换为人类可读字符串,这些字符串以自然语言格式描述持续时间,如“2 小时前”、“3 天后”等。

The naturaldelta() function converts time deltas (duration) into human-readable strings that describe the duration in a natural language format such as "2 hours ago", "3 days from now", etc.

以下是使用 Python Humanize 包的 naturaldelta() 函数的示例 −

Following is the example of using the naturaldelta() function of the Python Humanize Package −

from datetime import timedelta
import humanize

Using naturaldelta for time durations
delta1 = timedelta(days=3, hours=5)
print(f"Time duration: {humanize.naturaldelta(delta1)} from now")

Example of a future duration (delta2)
delta2 = timedelta(hours=5)
print(f"Future duration: in {humanize.naturaldelta(delta2)}")

Example of a past duration (delta3)
delta3 = timedelta(days=1, hours=3)
print(f"Past duration: {humanize.naturaldelta(delta3)} ago")

Output

Time duration: 3 days from now
Future duration: in 5 hours
Past duration: a day ago