Skip to content

Instantly share code, notes, and snippets.

@alaroldai
Created April 22, 2014 03:12
Show Gist options
  • Save alaroldai/11164231 to your computer and use it in GitHub Desktop.
Save alaroldai/11164231 to your computer and use it in GitHub Desktop.
Format input files into columns, split by whitespace
#!/usr/bin/env python3
import sys, argparse
def columnize(fname, ncols):
f = open(fname, 'r')
lines = list(map(lambda l: l.split(), f.readlines()))
col = 0
cols = zip(*lines)
cols = list(map(lambda c: max((len(w) for w in c)), cols))[:ncols]
print(ncols)
f.close()
f = open(fname, 'w')
print(list(cols))
for l in lines:
for i, w in enumerate(l):
f.write(w)
ss = 1
if i < len(cols):
ss += cols[i] - len(w)
f.write(' ' * ss)
f.write('\n')
f.close()
def main():
p = argparse.ArgumentParser(description = 'Format input files into columns, split by whitespace')
p.add_argument('files', nargs='*')
p.add_argument('-c', '--ncols', help = 'The number of columns to use. Any extra whitespace will be ignored.')
a = p.parse_args()
for f in a.files:
columnize(f, max(int(a.ncols) - 1, 1))
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment