gpt4 book ai didi

python - 使用 csv 数据创建表

转载 作者:太空狗 更新时间:2023-10-30 01:01:15 25 4
gpt4 key购买 nike

给定一个包含以下内容的 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 -'s 和 |'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|
+------------+------------+------------+

不知道文件中有多少列:

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|
+------------+------------+------------+

关于python - 使用 csv 数据创建表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27886954/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com