如何将文本文件格式化为表格格式?

问题描述 投票:0回答:2

我试图从文本文件中显示一堆行作为表。文本文件看起来像这样:

capital|What is the capital of Egypt?|Cairo|3
pi|What is pi to two digits?|3.14|3
dozen|How many eggs in a dozen?|12|1
president|Who was the first president?|Washington|1

我想让我的代码吐出一个格式化的输出,看起来像这样:

capital      What is the capital of Egypt?   Cairo        3
pi           What is pi to two digits?       3.14         3
dozen        How many eggs in a dozen?       12           1
president    Who was the first president?    Washington   1

这是我提出的代码,但输出远不如我想要的那样。

f = open('quest_load.txt', 'r')
contents = f.read()
contents1 = contents.replace('|','     ')
print(contents1)
f.close()
python output tabular
2个回答
0
投票

循环遍历数据一次,以发现每列的最大宽度:

with open('quest_load.txt', 'r') as f:
    for i, line in enumerate(f):
        if i == 0:
            max_widths = [len(col) for col in line.split('|')]
            continue
        max_widths = [
            max(len(col), curr_max)
            for col, curr_max in zip(line.split('|'), max_widths)
        ]

然后再次循环打印列,根据最大宽度格式化每列:

with open('quest_load.txt', 'r') as f:
    for line in f:
        content = line.split('|')
        formatted = [
            f'{substr: <{width}}'
            for substr, width in zip(content, max_widths)
        ]
        print('\t'.join(formatted), end='')

输出:

capital     What is the capital of Egypt?   Cairo       3
pi          What is pi to two digits?       3.14        3
dozen       How many eggs in a dozen?       12          1
president   Who was the first president?    Washington  1

0
投票

假设sl1代表文件中的行:

import sys

from collections import defaultdict

sl1 = [
    "capital|What is the capital of Egypt?|Cairo|3",
    "pi|What is pi to two digits?|3.14|3",
    "dozen|How many eggs in a dozen?|12|1",
    "president|Who was the first president?|Washington|1"
]
if not sl1:
    sys.exit(1)

# get the widths of the columns and the rows themselves
rows = []
col_lengths = defaultdict(list)

firs_row = sl1[0].split("|")
col_count = len(firs_row)

for s in sl1:
    col_vals = s.split("|")
    rows.append(col_vals)
    [col_lengths[i].append(len(col_val)) for i, col_val in enumerate(col_vals)]

# find the maximum for each column
for k, vals in col_lengths.items():
    col_lengths[k] = max(vals) + 5  # 5 is a bit of extra spacing

# create a dynamic format based on the widths of the columns
table_format = "{{:{}}}" * col_count
table_format = table_format.format(*col_lengths.values())

# at last print the rows
for row in rows:
    print(table_format.format(*row))

结果将是:

capital       What is the capital of Egypt?     Cairo          3     
pi            What is pi to two digits?         3.14           3     
dozen         How many eggs in a dozen?         12             1     
president     Who was the first president?      Washington     1
© www.soinside.com 2019 - 2024. All rights reserved.