Python中有没有文本版本的直方图或制表库
后台程序想定期输出统计数据到文件里。不知道有没有类似直方图,或者制表的库可用。
类似 pylint 的 report 生成的那种文本版制表图
Python中有没有文本版本的直方图或制表库
1 回复
有,Python里有几个好用的库可以生成文本直方图和表格。
对于文本直方图,histogram 库最简单直接,它专门干这个。用 pip install histogram 安装,然后像这样用:
from histogram import histogram
import random
# 生成一些随机数据
data = [random.randint(1, 10) for _ in range(100)]
# 生成并打印文本直方图
print(histogram(data, bins=10))
对于更复杂的文本表格,tabulate 是首选,功能强且格式漂亮。用 pip install tabulate 安装:
from tabulate import tabulate
# 准备数据
table_data = [
["Alice", 28, "Engineer"],
["Bob", 34, "Designer"],
["Charlie", 45, "Manager"]
]
headers = ["Name", "Age", "Job"]
# 打印表格,可以选不同格式,比如'plain', 'simple', 'grid', 'fancy_grid'
print(tabulate(table_data, headers=headers, tablefmt="grid"))
如果只是想在终端里快速画个简单的ASCII直方图,标准库 statistics 里的 quantiles 配合字符串乘法也能凑合:
import statistics
import random
data = [random.gauss(0, 1) for _ in range(50)]
freq, bins = statistics.quantiles(data, n=10)
for b, f in zip(bins, freq):
print(f"{b:5.2f} | {'#' * int(f * 20)}")
总结:要文本直方图用 histogram,要制表用 tabulate。

