Skip to content

Instantly share code, notes, and snippets.

@bas080
Created February 6, 2015 09:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save bas080/e729c797913cfa7ae698 to your computer and use it in GitHub Desktop.
Save bas080/e729c797913cfa7ae698 to your computer and use it in GitHub Desktop.
Easily columize code. Example would be "columnice.py ,". This will columize the text using the comma ',' as the delimeter.
#!/usr/bin/env python
import sys
def matrix( text, seperator_x='\t', seperator_y='\n'):
table = []
rows = text.split( seperator_y )
for index, row in enumerate( rows ):
table.insert( index, row.split( seperator_x ) )
return table
def sizes( table=[] ):
sizes = []
for row in table:
for index, field in enumerate(row):
try:
sizes[index] = max( len(field), sizes[index] )
except Exception, e:
sizes.insert( index, len(field) )
pass
return sizes
def collumns( table=[], sizes=[], seperator='\t' ):
for row in table:
line = ''
for index, field in enumerate(row):
field_size = len(field)
field_max = sizes[index]
size_diff = field_max - field_size
if index < len(row)-1:
line = line + field + seperator + ( ' ' * size_diff )
else:
line = line + field
print line
line = ''
try:
sepe = sys.argv[1]
except Exception, e:
raise e
sys.exit(1)
text = sys.stdin.read()
t = matrix( text, sepe )
s = sizes( t )
c = collumns( t, s, sepe )
sys.exit(0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment