Table creation with csv data
给出一个包含如下内容的csv:
1 2 3 | Colour, Red, Black, Blue Taste, Good, Bad, Disgusting Smell, Pleasant, Deceptive, Intolerable |
我怎样才能用python打印出来,使它看起来像这样:
1 2 3 4 5 6 7 | +-------+-----------+-----------+ |Colour |Taste | Smell | +-------+-----------+-----------+ | Red |Good | Pleasant | | Black | Bad | Deceptive | | Blue | Disgusting|Intolerable| +-------+-----------+-----------+ |
我是否必须使用+'s-'s和手动创建表,并考虑到各自列的最长字符串,或者是否有内置的方法?我搜索了python表,但没有发现与问题相关的内容。另外,我手工输入的示例表在每个单元格中都不是对称的(没有正确地"对齐")。
问题的症结在于+-表的创建。
怎么办?
这不是内置的,但您可以使用术语:
1 2 3 4 5 6 7 | 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) |
要安装,请执行以下操作:
1 | pip install terminaltables |
最接近内置方法的是使用str.format:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | 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| +------------+------------+------------+ |
不知道文件中有多少列:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | 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| +------------+------------+------------+ |