用csv d创建表

2024-03-29 15:02:02 发布

您现在位置:Python中文网/ 问答频道 /正文

给出一个csv,内容如下:

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

如何用python将其打印出来,使其看起来像这样:

^{pr2}$

我是否必须手动创建包含+'s-'和|的表,并考虑到各自列的最长字符串,还是有内置的方法?我确实搜索了python表,但是没有找到与该问题相关的内容。另外,我手动输入的示例表在每个单元格中不是对称的(不是“对齐”的)。在

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

怎么办?在


Tags: csv内容bluered手动blackbadgood
2条回答

最接近内置方法的是使用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|
+      +      +      +

不知道文件中有多少COL:

^{pr2}$

这不是内置的,但您可以使用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)

要安装,请执行以下操作:

^{pr2}$

相关问题 更多 >