使用csv数据创建表

时间:2015-01-11 12:20:29

标签: python

给出一个带有类似内容的csv:

Colour, Red, Black, Blue
Taste, Good, Bad, Disgusting
Smell, Pleasant, Deceptive, Intolerable

如何在python中打印出来,使它看起来像这样:

+-------+-----------+-----------+
|Colour |Taste      | Smell     |
+-------+-----------+-----------+
|  Red  |Good       | Pleasant  |
| Black | Bad       | Deceptive |
| Blue  | Disgusting|Intolerable|
+-------+-----------+-----------+

我是否必须使用+' s来手动创建表格,并且考虑到各列的最长字符串或是否有内置方法为了这?我确实搜索了python表,但没有出现任何问题。我手动输入的示例表在每个单元格中都不对称(不是"对齐"正确)。

问题的关键是+ - |表创建。

怎么办?

2 个答案:

答案 0 :(得分:3)

与内置方法最接近的是使用str.format

import csv
with open("output.txt") as f:
    lines = list(csv.reader(f,delimiter=","))
    # get longest string for alignment
    mx_len = len(max((max(ele,key=len) for ele in lines),key=len))
    # transpose the list items
    zipped = zip(*lines)
    # get header/first row 
    row1 = zipped[0]
    # how many "-" we need depends on longests word length
    pattern = "-"*mx_len
    f = ("+{pat}+{pat}+{pat}+".format(pat=pattern))
    print(f)
    # pass in mx_len as align value
    print("|{:<{i}}|{:<{i}}|{:<{i}}|".format(*row1,i=mx_len))
    print(f)
    # print the rest of the transposed data excluding column 1/row1
    for a, b, c in zipped[1:]:
        print("|{:<{i}}|{:<{i}}|{:<{i}}|".format(a.rstrip(),b.rstrip(),c.rstrip(),i=mx_len))
    print(f)

+------------+------------+------------+
|Colour      |Taste       |Smell       |
+------------+------------+------------+
| Red        | Good       | Pleasant   |
| Black      | Bad        | Deceptive  |
| Blue       | Disgusting | Intolerable|
+------------+------------+------------+

无法准确知道文件中有多少列:

with open("output.txt") as f:
    lines = list(csv.reader(f, delimiter=","))
    mx_len = len(max((max(ele, key=len) for ele in lines), key=len))
    zipped = zip(*lines)
    row1 = zipped[0]
    ln = len(row1)
    pattern = "-" * mx_len
    f = (("+{pat}" * ln + "+").format(pat=pattern))
    print(f)
    print(("|{:<{i}}" * ln + "|").format(*row1, i=mx_len))
    print(f)
    for row in zipped[1:]:
        print(("|{:<{i}}" * ln + "|").format(*row, i=mx_len))
    print(f)

+------------+------------+------------+
|Colour      |Taste       |Smell       |
+------------+------------+------------+
| Red        | Good       | Pleasant   |
| Black      | Bad        | Deceptive  |
| Blue       | Disgusting | Intolerable|
+------------+------------+------------+

答案 1 :(得分:3)

这不是内置的,但您可以使用terminaltables

from terminaltables import AsciiTable

with open('test.csv') as f:
    table_data = [line.split(",") for line in f]
    transposed = [list(i) for i in zip(*table_data)] 

print(AsciiTable(transposed).table)

安装只需执行:

pip install terminaltables