12

TL; DR -> PyPi 上是否有一个表格写入模块(我找不到任何),它将列表作为参数并从这些列表中制作一个表格。我问这个是因为我看过 PyPI,但我没有发现任何类似于实际打印字符串或将字符串写入文件的东西。

想象一下有很多统计数据,并且必须将它们整齐地写在一个表格中,就像这样,(我一直在尝试教一堂关于不同排序算法之间差异的课程)(另外,请注意示例这里给出的与下面给出的代码的输出不匹配。我这样做是为了解释我想要的内容,而不是制作必须滚动浏览的大块代码):

#########################
#   LENGTH ||| TIME(s)  #
#########################
#       0  ||| 0.00000  #
#     250  ||| 0.00600  #
#     500  ||| 0.02100  #
#     750  ||| 0.04999  #
#    1000  ||| 0.08699  #
#    1250  ||| 0.13499  #
#    1500  ||| 0.19599  #
#    1750  ||| 0.26900  #
#    2000  ||| 0.35099  #
#########################

理想情况下,我会写这样的东西来保存到文件中,如下所示。一组列表,一个列表包含一组值,另一个包含另一组对应的值。

if __name__ == '__main__':
    with open(os.path.join(os.path.dirname(__file__), 'Sort Stats', 'stats_exp.txt'), 'w') as stats:
        stats.write(
            "O-######################==#######################==#######################==######################-O\n")
        stats.writelines(
            "|{0:^23}||{1:^23}||{2:^23}||{3:^23}|\n".format("Bubble Sort", "Insertion Sort", "Merge Sort (R)",
                                                            "Merge Sort (I)"))
        stats.write(
            "|#######################||#######################||#######################||#######################|\n")
        stats.write(
            "|   LENGTH  |  TIME(s)  ||   LENGTH  |  TIME(s)  ||   LENGTH  |  TIME(s)  ||   LENGTH  |  TIME(s)  |\n")
        stats.write(
            "|#######################||#######################||#######################||#######################|\n")
        for times_taken, t1, t2, t3, t4 in zip(total_lengths, sort_times_bubble, sort_times_ins, sort_times_merge_r,
                                               sort_times_merge_i):
            stats.write(
                "|{0:^11}|{1:^11}||{2:^11}|{3:^11}||{4:^11}|{5:^11}||{6:^11}|{7:^11}|\n"
                .format(
                    times_taken, str(t1)[:6],
                    times_taken, str(t2)[:6],
                    times_taken, str(t3)[:6],
                    times_taken, str(t4)[:6],
                )
            )
        stats.write(
            "O-######################==#######################==#######################==######################-O\n")

    print "Data writing complete"

正如你所看到的,它并不完全漂亮,最重要的是它不是很容易扩展的东西,因为它几乎可以打印出一些东西。

我想要做的是为此创建一个模块并将其上传到 PyPI。但是,如果有人已经做了类似的东西,那么这将是浪费精力,我可以简单地分叉他们的存储库,而不必实际从头开始编写代码。

4

2 回答 2

27

PrettyTable module is what you need:

PrettyTable is a simple Python library designed to make it quick and easy to represent tabular data in visually appealing ASCII tables.

>>> import prettytable
>>> x = prettytable.PrettyTable(["Length", "Time"])
>>> x.add_row([0, 0.00000])
>>> x.add_row([250, 0.00600]) 
>>> x.add_row([500, 0.02100]) 
>>> x.add_row([750, 0.04999])    
>>> print x
+--------+---------+
| Length |   Time  |
+--------+---------+
|   0    |   0.0   |
|  250   |  0.006  |
|  500   |  0.021  |
|  750   | 0.04999 |
+--------+---------+

Or, texttable:

texttable is a module to generate a formatted text table, using ASCII characters.

>>> import texttable
>>> x = texttable.Texttable()
>>> x.add_rows([["Length", "Time"], [0, 0.00000], [250, 0.00600], [500, 0.02100], [750, 0.04999]])
>>> print x.draw()
+--------+-------+
| Length | Time  |
+========+=======+
| 0      | 0     |
+--------+-------+
| 250    | 0.006 |
+--------+-------+
| 500    | 0.021 |
+--------+-------+
| 750    | 0.050 |
+--------+-------+

Also see relevant thread: How can I pretty-print ASCII tables with Python?

于 2013-10-01T20:26:24.587 回答
7

我只是要从我这里抛出一个解决方案,我实际上是在上周写的,只是为了测试一些东西。它目前对所有内容进行右对齐,但添加一些对齐参数或其他东西会很简单。

def printTable (tbl, borderHorizontal = '-', borderVertical = '|', borderCross = '+'):
    cols = [list(x) for x in zip(*tbl)]
    lengths = [max(map(len, map(str, col))) for col in cols]
    f = borderVertical + borderVertical.join(' {:>%d} ' % l for l in lengths) + borderVertical
    s = borderCross + borderCross.join(borderHorizontal * (l+2) for l in lengths) + borderCross

    print(s)
    for row in tbl:
        print(f.format(*row))
        print(s)

例子:

>>> x = [['Length', 'Time(ms)'], [0, 0], [250, 6], [500, 21], [750, 50], [1000, 87], [1250, 135], [1500, 196], [1750, 269], [2000, 351]]
>>> printTable(x)
+--------+----------+
| Length | Time(ms) |
+--------+----------+
|      0 |        0 |
+--------+----------+
|    250 |        6 |
+--------+----------+
|    500 |       21 |
+--------+----------+
|    750 |       50 |
+--------+----------+
|   1000 |       87 |
+--------+----------+
|   1250 |      135 |
+--------+----------+
|   1500 |      196 |
+--------+----------+
|   1750 |      269 |
+--------+----------+
|   2000 |      351 |
+--------+----------+
于 2013-10-01T20:42:26.880 回答