鱼C论坛

 找回密码
 立即注册
查看: 1306|回复: 0

[作品展示] 【Python】命令行表格渲染器 v0.1.0

[复制链接]
发表于 2022-2-1 15:07:12 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
本帖最后由 ckblt 于 2022-2-1 15:06 编辑

我改进了一下我的表格渲染器,
给大家分享一下。

特别感谢@python爱好者. 的建议与支持!

  1. from typing import Union, List, Tuple, Set
  2. import random


  3. class Table:
  4.     @staticmethod
  5.     def random_table(
  6.         len_x: Union[int, None] = None, len_y: Union[int, None] = None
  7.     ) -> List[List]:
  8.         """
  9.         随机生成一个二维列表

  10.         参数:
  11.         `len_x: int | None` -- 二维列表的长度
  12.         `len_y: int | None` -- 二维列表的宽度
  13.         """
  14.         x = random.randint(2, 5) if len_x == None else len_x
  15.         y = random.randint(2, 5) if len_y == None else len_y
  16.         return [[random.randint(0, 10000) for _ in range(x)] for _ in range(y)]

  17.     def __init__(self, table: List[List]):
  18.         """
  19.         初始化 Table

  20.         参数:
  21.         `table: List[List]` -- 表格
  22.         """
  23.         self.table = table.table if isinstance(table, Table) else [i for i in table]
  24.         self.length = len(self.table[0]), len(self.table)
  25.         self.__check()

  26.     def __check(self):
  27.         """
  28.         检查 self.table 是否合法
  29.         """
  30.         temp = set([len(x) for x in self.table])
  31.         if len(temp) != 1:
  32.             raise Exception()

  33.     def __no_list_list(self, x, no_tuples=False, no_sets=False):
  34.         new_list = []

  35.         for i in x:
  36.             if (
  37.                 (isinstance(i, list))
  38.                 or (no_tuples and isinstance(i, tuple))
  39.                 or (no_sets and isinstance(i, set))
  40.             ):
  41.                 new_list.extend(self.__no_list_list(i, no_tuples, no_sets))
  42.             else:
  43.                 new_list.append(i)

  44.         return new_list

  45.     def render(self, isSquare=False, spacing=4, prop=3) -> str:
  46.         """
  47.         以普通模式渲染 self.table

  48.         参数:
  49.         `isSquare: bool` -- 正方形模式
  50.         `spacing: int` -- 间距, 需要大于 0
  51.         `prop: int | float` -- 方形的长宽比例,使它接近正方形
  52.         """
  53.         col_spaces = spacing
  54.         l = self.__no_list_list(self.table)
  55.         rendered = ""

  56.         # 每列之间的空,存储到 col_spaces
  57.         for i in l:
  58.             if len(str(i)) > col_spaces - spacing:
  59.                 col_spaces = len(str(i)) + spacing

  60.         # 正式渲染
  61.         for i_i in range(self.length[1]):
  62.             i = self.table[i_i]
  63.             for j in i:
  64.                 rendered += str(j) + " " * (col_spaces - len(str(j)))

  65.             if i_i != self.length[1] - 1:
  66.                 if isSquare:
  67.                     rendered += "\n" * round(col_spaces / prop)
  68.                 else:
  69.                     rendered += "\n"

  70.         return rendered

  71.     def chart(
  72.         self,
  73.         isSquare=False,
  74.         align: Union["left", "center", "right"] = "left",
  75.         align_y: Union["top", "center", "bottom"] = "top",
  76.         spacing=4,
  77.         prop=3,
  78.     ) -> str:
  79.         """
  80.         以图表模式渲染 self.table

  81.         参数:
  82.         `isSquare: bool` -- 正方形模式
  83.         `align: "left" | "center" | "right"` -- 左右对齐
  84.         `align_y: "top" | "center" | "bottom"` -- 上下对齐, 需要让 `isSquare` 为 `True`
  85.         `spacing: int` -- 间距, 需要大于 0
  86.         `prop: int | float` -- 方形的长宽比例,使它接近正方形
  87.         """
  88.         col_spaces = spacing
  89.         l = self.__no_list_list(self.table)
  90.         rendered = ""

  91.         # 每列之间的空,存储到 col_spaces
  92.         for i in l:
  93.             if len(str(i)) > col_spaces - spacing:
  94.                 col_spaces = len(str(i)) + spacing

  95.         # 正式渲染
  96.         rendered += "-" * ((col_spaces + 1) * self.length[0] + 1) + "\n"
  97.         for i_i in range(self.length[1]):
  98.             i = self.table[i_i]
  99.             temp = ""
  100.             for j in i:
  101.                 if align == "left":
  102.                     temp += str(j) + " " * (col_spaces - len(str(j))) + "|"
  103.                 elif align == "center":
  104.                     a = (col_spaces - len(str(j))) // 2
  105.                     b = ((col_spaces - len(str(j)))) - a
  106.                     temp += " " * a + str(j) + " " * b + "|"
  107.                     del a, b
  108.                 elif align == "right":
  109.                     temp += " " * (col_spaces - len(str(j))) + str(j) + "|"

  110.             if isSquare:
  111.                 if align_y == "top":
  112.                     rendered += (
  113.                         "|"
  114.                         + temp
  115.                         + "\n"
  116.                         + (("|" + " " * col_spaces) * (self.length[0] + 1) + "\n")
  117.                         * round(col_spaces / prop)
  118.                     )
  119.                 elif align_y == "center":
  120.                     a = round(col_spaces / prop / 2)
  121.                     b = round(col_spaces / prop) - a
  122.                     rendered += (
  123.                         ((("|" + " " * col_spaces) * (self.length[0] + 1) + "\n") * a)
  124.                         + "|"
  125.                         + temp
  126.                         + "\n"
  127.                         + ((("|" + " " * col_spaces) * (self.length[0] + 1) + "\n") * b)
  128.                     )
  129.                     del a, b
  130.                 elif align_y == "bottom":
  131.                     rendered += (
  132.                         (("|" + " " * col_spaces) * (self.length[0] + 1) + "\n")
  133.                         * round(col_spaces / prop)
  134.                         + "|"
  135.                         + temp
  136.                         + "\n"
  137.                     )
  138.             else:
  139.                 rendered += "|" + temp + "\n"
  140.             rendered += "-" * ((col_spaces + 1) * self.length[0] + 1) + "\n"

  141.         return rendered
复制代码


使用方法:
用 Table.random_table(列表长度, 列表宽度) 来创建一个二维列表
用 t = Table(你的二维列表) 来创建表格
用 t.render() 来渲染
用 t.chart() 来以图表方式渲染

例子:
  1. l = Table.random_table(3, 3)  # 创建一个 3x3 的随机二维数组
  2. t = Table(l)  # 创建一个表格
  3. print(t.render())
  4. print("分隔线")
  5. print(t.chart())
复制代码


输出:
  1. 2139    3152    757
  2. 3783    2615    8039
  3. 1156    6488    9565
  4. 分隔线
  5. ----------------------------
  6. |2139    |3152    |757     |
  7. ----------------------------
  8. |3783    |2615    |8039    |
  9. ----------------------------
  10. |1156    |6488    |9565    |
  11. ----------------------------
复制代码

评分

参与人数 1鱼币 +5 收起 理由
python爱好者. + 5 鱼C有你更精彩^_^

查看全部评分

小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-5-2 13:58

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表