Как отформатировать текстовый файл в четный табличный формат? - PullRequest
0 голосов
/ 06 апреля 2019

Я пытаюсь отобразить несколько строк из текстового файла в виде таблицы.Текстовый файл выглядит примерно так:

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 голосов
/ 06 апреля 2019

Предполагая, что 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
0 голосов
/ 06 апреля 2019

Обведите данные один раз, чтобы определить максимальную ширину каждого столбца:

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