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

时间:2019-04-05 21:35:20

标签: python output tabular

我试图将文本文件中的一堆行显示为表格。文本文件如下所示:

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()

2 个答案:

答案 0 :(得分: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

答案 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