Python Forum
a script i need: column alignment
Thread Rating:
  • 1 Vote(s) - 3 Average
  • 1
  • 2
  • 3
  • 4
  • 5
a script i need: column alignment
#9
i went ahead and coded my own. i'll post it below so you can red mark it for my bad coding. but it does work on test data and a file with a mix of "tar tvf" listing of different tarballs, prefix with paths to that tarball.

aligncolumns.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""stdin to stdout,align columns, right padded except for numbers."""
from __future__ import print_function
from sys import stdin, stdout

input = stdin
output = stdout

flag = []
wide = []
save = []

for line in input:
    cols = line.rstrip().split()
    save.append(cols)
    if len(flag) < len(cols):
        flag = flag + [0]*(len(cols)-len(flag))
        wide = wide + [0]*(len(cols)-len(wide))
    for x in range(len(cols)):
        wide[x] = max(wide[x],len(cols[x]))
        try:
            float(cols[x])
        except:
            flag[x] = 1
input.close()

for cols in save:
    for x in range(len(cols)):
        pad = ' '*(wide[x]-len(cols[x]))
        if flag[x]:
            cols[x] = cols[x]+pad
        else:
            cols[x] = pad+cols[x]
    print(' '.join(cols),file=output)
output.close()

exit(0)
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply


Messages In This Thread
a script i need: column alignment - by Skaperen - Jan-09-2019, 12:16 AM
RE: a script i need: column alignment - by Larz60+ - Jan-09-2019, 05:43 AM
RE: a script i need: column alignment - by Skaperen - Jan-09-2019, 03:57 PM
RE: a script i need: column alignment - by nilamo - Jan-09-2019, 04:46 PM
RE: a script i need: column alignment - by Skaperen - Jan-11-2019, 03:41 PM
RE: a script i need: column alignment - by nilamo - Jan-11-2019, 04:24 PM
RE: a script i need: column alignment - by snippsat - Jan-11-2019, 05:46 PM
RE: a script i need: column alignment - by Skaperen - Jan-12-2019, 07:06 PM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020