鉴于csv的内容类似于:
Colour, Red, Black, Blue
Taste, Good, Bad, Disgusting
Smell, Pleasant, Deceptive, Intolerable
Run Code Online (Sandbox Code Playgroud)
如何在python中打印出来,使它看起来像这样:
+-------+-----------+-----------+
|Colour |Taste | Smell |
+-------+-----------+-----------+
| Red |Good | Pleasant |
| Black | Bad | Deceptive |
| Blue | Disgusting|Intolerable|
+-------+-----------+-----------+
Run Code Online (Sandbox Code Playgroud)
我是否必须使用+'s和|来考虑相应列的最长字符串来手动创建表格,还是有内置的方法?我确实搜索了python表,但没有出现任何问题.我手动输入的示例表在每个单元格中都不对称(未正确"对齐").
问题的关键是+ - | 表创建.
该怎么办?
最接近内置方法的是使用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|
+------------+------------+------------+
Run Code Online (Sandbox Code Playgroud)
不知道文件中有多少列:
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|
+------------+------------+------------+
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
162 次 |
| 最近记录: |