用于将 2D Python 列表转换为花哨的 ASCII/Unicode 表的模块

3,354 阅读4分钟

本文正在参加「Python主题月」,详情查看 活动链接

table2ascii

用于将 2D Python 列表转换为花哨的 ASCII 表的模块。Table2Ascii 可让您在终端和 Discord 上显示漂亮的表格。

📥 安装

pip install table2ascii

image.png

🧑‍💻 用法

将列表转换为 ASCII 表

from table2ascii import table2ascii

output = table2ascii(
    header=["#", "G", "H", "R", "S"],
    body=[["1", "30", "40", "35", "30"], ["2", "30", "40", "35", "30"]],
    footer=["SUM", "130", "140", "135", "130"],
)

print(output)

输出:

image.png

设置第一个或最后一个列标题

from table2ascii import table2ascii

output = table2ascii(
    body=[["Assignment", "30", "40", "35", "30"], ["Bonus", "10", "20", "5", "10"]],
    first_col_heading=True,
)

print(output)

输出:

image.png

设置列宽和对齐方式

from table2ascii import table2ascii, Alignment

output = table2ascii(
    header=["#", "G", "H", "R", "S"],
    body=[["1", "30", "40", "35", "30"], ["2", "30", "40", "35", "30"]],
    first_col_heading=True,
    column_widths=[5] * 5,  # [5, 5, 5, 5, 5]
    alignments=[Alignment.LEFT] + [Alignment.RIGHT] * 4, # First is left, remaining 4 are right
)

print(output)

输出:

image.png

使用预设样式

from table2ascii import table2ascii, PresetStyle

output = table2ascii(
    header=["First", "Second", "Third", "Fourth"],
    body=[["10", "30", "40", "35"], ["20", "10", "20", "5"]],
    column_widths=[10] * 4,
    style=PresetStyle.ascii_box
)

print(output)

输出:

image.png

定义自定义样式

查看TableStyle更多信息和PresetStyle示例。

from table2ascii import table2ascii, TableStyle

my_style = TableStyle.from_string("*-..*||:+-+:+     *''*")

output = table2ascii(
    header=["First", "Second", "Third"],
    body=[["10", "30", "40"], ["20", "10", "20"], ["30", "20", "30"]],
    style=my_style
)

print(output)

输出:

image.png

🎨 预设样式

在此处查看所有预设样式的列表。

⚙️ 选项

所有参数都是可选的。

选项类型默认描述
headerList[str]None表的第一行由标题行分隔符分隔
bodyList[List[str]]None表格主要部分的行列表
footerList[str]None表的最后一行由标题行分隔符分隔
column_widthsList[int]自动的每列以字符为单位的列宽列表
alignmentsList[int]全部居中每列的对齐方式 (例如[Alignment.LEFT, Alignment.CENTER, Alignment.RIGHT]
first_col_headingboolFalse是否在第一列后添加标题列分隔符
last_col_headingboolFalse是否在最后一列前添加标题列分隔符

👨‍🎨 用例

不和谐消息和嵌入

  • 在 Discord 上的 Markdown 代码块中很好地显示表格
  • 用于使用Discord.py制作 Discord 机器人

image.png

终端输出

  • 只要完全支持等宽字体,表格就会很好地显示
  • 表格让终端输出看起来更专业

image.png

🧰 发展

运行测试(pytest)

python setup.py test

去绒(flake8):

python setup.py lint

GitHub

github.com/wanghao221/…

快速总结——Python 程序实现摩斯密码翻译器

以上就是本篇文章的全部内容,用于将 2D Python 列表转换为花哨的 ASCII/Unicode 表的模块。我希望本篇博客能够帮助到大家,博主也在学习进行中,如有什么错误的地方还望批评指正。如果你喜欢这篇文章并希望看到更多此类文章,可以看看这里(Github/Gitee) 这里汇总了我的全部原创及作品源码,关注我以查看更多文章。

🥇 Python 进行数据可视化系列汇总

🥈 Python实用小程序

🧵 Python基础知识

🚀 技巧和面试题

如果你真的从这篇文章中学到了一些新东西,喜欢它,收藏它并与你的小伙伴分享。🤗最后,不要忘了❤或📑支持一下哦