如何为Python PrettyTable创建页脚
我希望在我的PrettyTable中添加一个页脚,将上面几行中存储的数据相加。我在脚本中创建了一个计数,但我想将其添加到表中 我必须创建下表的代码如下(如何为Python PrettyTable创建页脚,python,prettytable,Python,Prettytable,我希望在我的PrettyTable中添加一个页脚,将上面几行中存储的数据相加。我在脚本中创建了一个计数,但我想将其添加到表中 我必须创建下表的代码如下(.add\u row处于循环中): …生成一个如下所示的表: +--------------------------+-----------+ | Projects | Number | +--------------------------+-----------+ | Project A
.add\u row
处于循环中):
…生成一个如下所示的表:
+--------------------------+-----------+
| Projects | Number |
+--------------------------+-----------+
| Project A | 5 |
| Project B | 9 |
| Project C | 8 |
| Project D | 2 |
+--------------------------+-----------+
…但我正在寻找创建上表的功能,该表底部有一个摘要页脚:
+--------------------------+-----------+
| Projects | Number |
+--------------------------+-----------+
| Project A | 5 |
| Project B | 9 |
| Project C | 8 |
| Project D | 2 |
+--------------------------+-----------+
| Total | 24 |
+--------------------------+-----------+
我已经在线搜索了模块文档:,但没有看到任何对页脚的引用,我发现令人惊讶的是,给定的页眉就是页脚。这可以在PrettyTable中完成吗,或者有人可以推荐另一个具有此功能的Python模块吗?您可以使用它周围的小技巧:
import texttable
table = texttable.Texttable()
table.add_rows([['Projects', 'Number'],
['Project A\nProject B\nProject C\nProject D', '5\n9\n8\n2'],
['Total', 24]])
print(table.draw())
输出:
+-----------+--------+
| Projects | Number |
+===========+========+
| Project A | 5 |
| Project B | 9 |
| Project C | 8 |
| Project D | 2 |
+-----------+--------+
| Total | 24 |
+-----------+--------+
您可以在其周围使用小黑客:
import texttable
table = texttable.Texttable()
table.add_rows([['Projects', 'Number'],
['Project A\nProject B\nProject C\nProject D', '5\n9\n8\n2'],
['Total', 24]])
print(table.draw())
输出:
+-----------+--------+
| Projects | Number |
+===========+========+
| Project A | 5 |
| Project B | 9 |
| Project C | 8 |
| Project D | 2 |
+-----------+--------+
| Total | 24 |
+-----------+--------+
并没有单独的函数来创建pretty表中的页脚。然而,您可以做一些小技巧来创建,以防您只使用如下所示的漂亮表
sum = 0
for row in outTbl:
sum = sum + int(row.get_string(fields=["Number"]).split('\n')[3].replace('|','').replace(' ',''))
outTbl.add_row(['------------','-----------'])
outTbl.add_row(['Total',sum])
print (outTbl)
或者,如果您正在寻找具有页脚的特定函数,您可以查看
对于不同的方法,您可以使用在表格中没有单独的函数来创建页脚。然而,您可以做一些小技巧来创建,以防您只使用如下所示的漂亮表
sum = 0
for row in outTbl:
sum = sum + int(row.get_string(fields=["Number"]).split('\n')[3].replace('|','').replace(' ',''))
outTbl.add_row(['------------','-----------'])
outTbl.add_row(['Total',sum])
print (outTbl)
或者,如果您正在寻找具有页脚的特定函数,您可以查看
对于不同的方法,您可以使用在检查了pretty table的源代码之后,您可以看到在打印表格之后,您可以得到每个列宽。使用此选项,您可以自己创建一个页脚,因为pretty table不提供该选项。我的做法如下:
from prettytable import PrettyTable
t = PrettyTable(['Project', 'Numbers'])
t.add_row(['Project A', '5'])
t.add_row(['Project B', '9'])
t.add_row(['Project C', '8'])
t.add_row(['Project D', '2'])
print(t)
total = '24'
padding_bw = (3 * (len(t.field_names)-1))
tb_width = sum(t._widths)
print('| ' + 'Total' + (' ' * (tb_width - len('Total' + total)) +
' ' * padding_bw) + total + ' |')
print('+-' + '-' * tb_width + '-' * padding_bw + '-+')
以下是输出:
+-----------+---------+
| Project | Numbers |
+-----------+---------+
| Project A | 5 |
| Project B | 9 |
| Project C | 8 |
| Project D | 2 |
+-----------+---------+
| Total 24 |
+---------------------+
只需更改代码中的total var,一切都应该正常运行在检查了pretty table的源代码后,您可以看到,在打印表格后,您可以获得每个列宽。使用此选项,您可以自己创建一个页脚,因为pretty table不提供该选项。我的做法如下:
from prettytable import PrettyTable
t = PrettyTable(['Project', 'Numbers'])
t.add_row(['Project A', '5'])
t.add_row(['Project B', '9'])
t.add_row(['Project C', '8'])
t.add_row(['Project D', '2'])
print(t)
total = '24'
padding_bw = (3 * (len(t.field_names)-1))
tb_width = sum(t._widths)
print('| ' + 'Total' + (' ' * (tb_width - len('Total' + total)) +
' ' * padding_bw) + total + ' |')
print('+-' + '-' * tb_width + '-' * padding_bw + '-+')
以下是输出:
+-----------+---------+
| Project | Numbers |
+-----------+---------+
| Project A | 5 |
| Project B | 9 |
| Project C | 8 |
| Project D | 2 |
+-----------+---------+
| Total 24 |
+---------------------+
只要更改代码中的总var,一切都会正常运行我今天遇到了同样的问题,并使用以下方法将我表格的最后n行视为结果行,结果行由水平行分隔(就像分隔页眉的行): 这将产生以下输出: +-----------+---------+ | Project | Numbers | +-----------+---------+ | Project A | 5 | | Project B | 9 | | Project C | 8 | +-----------+---------+ | Project D | 2 | +-----------+---------+ +-----------+---------+ |项目编号| +-----------+---------+ |项目A | 5| |项目B | 9| |项目C | 8| +-----------+---------+ |D|2项目| +-----------+---------+
今天我遇到了同样的问题,并使用以下方法将表格的最后n行视为结果行,这些结果行由水平线分隔(就像分隔页眉的结果行一样): 这将产生以下输出: +-----------+---------+ | Project | Numbers | +-----------+---------+ | Project A | 5 | | Project B | 9 | | Project C | 8 | +-----------+---------+ | Project D | 2 | +-----------+---------+ +-----------+---------+ |项目编号| +-----------+---------+ |项目A | 5| |项目B | 9| |项目C | 8| +-----------+---------+ |D|2项目| +-----------+---------+
我偷了@Niels solution,并使用此函数在最后一行
num\u footers
之前使用分隔符打印:
def print_with_footer(ptable, num_footers=1):
""" Print a prettytable with an extra delimiter before the last `num` rows """
lines = ptable.get_string().split("\n")
hrule = lines[0]
lines.insert(-(num_footers + 1), hrule)
print("\n".join(lines))
我偷了@Niels solution,并使用此函数在最后一行
num\u footers
之前使用分隔符打印:
def print_with_footer(ptable, num_footers=1):
""" Print a prettytable with an extra delimiter before the last `num` rows """
lines = ptable.get_string().split("\n")
hrule = lines[0]
lines.insert(-(num_footers + 1), hrule)
print("\n".join(lines))
我知道我迟到了,但我已经创建了一个函数来自动将“总计”行追加到表中。暂时不解决列是否比表宽 蟒蛇3.6++ 功能:
def table_footer(tbl, text, dc):
res = f"{tbl._vertical_char} {text}{' ' * (tbl._widths[0] - len(text))} {tbl._vertical_char}"
for idx, item in enumerate(tbl.field_names):
if idx == 0:
continue
if not item in dc.keys():
res += f"{' ' * (tbl._widths[idx] + 1)} {tbl._vertical_char}"
else:
res += f"{' ' * (tbl._widths[idx] - len(str(dc[item])))} {dc[item]} {tbl._vertical_char}"
res += f"\n{tbl._hrule}"
return res
用法:
tbl = PrettyTable()
tbl.field_names = ["Symbol", "Product", "Size", "Price", "Subtotal", "Allocation"]
tbl.add_row([......])
print(tbl)
print(table_footer(tbl, "Total", {'Subtotal': 50000, 'Allocation': '29 %'}
+--------+-------------------------------+-------+---------+----------+------------+
| Symbol | Product | Size | Price | Subtotal | Allocation |
+--------+-------------------------------+-------+---------+----------+------------+
| AMD | Advanced Micro Devices Inc | 999.9 | 75.99 | 20000.0 | 23.00 |
| NVDA | NVIDIA Corp | 88.8 | 570.63 | 30000.0 | 6.00 |
+--------+-------------------------------+-------+---------+----------+------------+
| Total | | | | 50000 | 29 % |
+--------+-------------------------------+-------+---------+----------+------------+
我知道我迟到了,但我已经创建了一个函数来自动将“总计”行追加到表中。暂时不解决列是否比表宽 蟒蛇3.6++ 功能:
def table_footer(tbl, text, dc):
res = f"{tbl._vertical_char} {text}{' ' * (tbl._widths[0] - len(text))} {tbl._vertical_char}"
for idx, item in enumerate(tbl.field_names):
if idx == 0:
continue
if not item in dc.keys():
res += f"{' ' * (tbl._widths[idx] + 1)} {tbl._vertical_char}"
else:
res += f"{' ' * (tbl._widths[idx] - len(str(dc[item])))} {dc[item]} {tbl._vertical_char}"
res += f"\n{tbl._hrule}"
return res
用法:
tbl = PrettyTable()
tbl.field_names = ["Symbol", "Product", "Size", "Price", "Subtotal", "Allocation"]
tbl.add_row([......])
print(tbl)
print(table_footer(tbl, "Total", {'Subtotal': 50000, 'Allocation': '29 %'}
+--------+-------------------------------+-------+---------+----------+------------+
| Symbol | Product | Size | Price | Subtotal | Allocation |
+--------+-------------------------------+-------+---------+----------+------------+
| AMD | Advanced Micro Devices Inc | 999.9 | 75.99 | 20000.0 | 23.00 |
| NVDA | NVIDIA Corp | 88.8 | 570.63 | 30000.0 | 6.00 |
+--------+-------------------------------+-------+---------+----------+------------+
| Total | | | | 50000 | 29 % |
+--------+-------------------------------+-------+---------+----------+------------+