Jump to content

Align columns: Difference between revisions

→‎{{header|Python}}: Changed 'record' to 'row' but left zip(*matrix) for transpose instead of using map which tends to be used less in Python now (they debated removing it from Python3).
mNo edit summary
(→‎{{header|Python}}: Changed 'record' to 'row' but left zip(*matrix) for transpose instead of using map which tends to be used less in Python now (they debated removing it from Python3).)
Line 301:
=={{header|Python}}==
<python>from StringIO import StringIO
 
textinfile = '''Given$a$text$file$of$many$lines,$where$fields$within$a$line$
are$delineated$by$a$single$'dollar'$character,$write$a$program
Line 308:
Further,$allow$for$each$word$in$a$column$to$be$either$left$
justified,$right$justified,$or$center$justified$within$its$column.'''
 
j2justifier = dict(L=str.ljust, R=str.rjust, C=str.center)
 
def aligner(infile, justification = 'L'):
''' \
Justify columns of textual tabular input where the recordrow separator is the newline
and the field separator is a 'dollar' character.
justification can be L, R, or C; (Left, Right, or Centered).
Return the justified output as a string
'''
assert justification in 'LRC', "justification can be L, R, or C; (Left, Right, or Centered)."
justifier = j2justifier[justification]
fieldsbyrow = [line.strip().split('$') for line in infile]
# pad to same number of fields per row
maxfields = max(len(row) for row in fieldsbyrow)
fieldsbyrow = [rowfields + ['']*(maxfields - len(rowfields))
for rowfields in fieldsbyrow]
# rotate
fieldsbycolumn = zip(*fieldsbyrow)
# calculate max fieldwidth per column
colwidths = map(lambda *column: [max(len(field) for field in column),
for column in *fieldsbyrow)fieldsbycolumn]
# pad fields in columns to colwidth with spaces
fieldsbyrowfieldsbycolumn = [map( [justifier(field, row, colwidthswidth) for field in column]
for rowwidth, column in fieldsbyrowzip(colwidths, fieldsbycolumn) ]
# rotate again
 
fieldsbyrow = zip(*fieldsbycolumn)
return "\n".join( " ".join(row) for row in fieldsbyrow)
 
for align in 'Left Right Center'.split():
infile = StringIO(textinfile)
Anonymous user
Cookies help us deliver our services. By using our services, you agree to our use of cookies.