public
Description: A text filter to format text into a table
Homepage: http://lucentbeing.com
Clone URL: git://github.com/sykora/tablefmt.git
tablefmt / tablefmt.py
100644 82 lines (59 sloc) 2.09 kb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
# Table formatting filter.
# P.C. Shyamshankar <sykora@lucentbeing.com>
# http://lucentbeing.com
 
from optparse import OptionParser
from sys import argv
 
def formatter(lines, inputDelimiter, outputDelimiter) :
    # Split lines based on inputDelimiter.
 
    lines = [filter(None, line.split(inputDelimiter)) for line in lines]
 
 
    # Assuming all rows are the same length,
    numColumns = len(lines[0])
    widths = []
 
    # Size of column = size of the largest entry in that column, + 1
    # TODO: Add delimiter support.
    for i in range(numColumns) :
        widths.append(max(len(line[i]) for line in lines))
 
    formatList = ["%%%ds"] * numColumns
 
    # There is probably a more efficient way (Time and Space) of doing this.
    output = []
    for i in range(len(lines)) :
        outputLine = formatList[:]
        outputLine = [((s % widths[j]) % lines[i][j])
                  for j, s in enumerate(formatList)]
        output.append(outputDelimiter.join(outputLine))
 
    return output
 
def parseOptions(argv) :
    parser = OptionParser()
 
    parser.add_option('-i', '--input-delimiter',
                      action = 'store',
                      type = 'string',
                      dest = 'inputDelimiter',
                      default = ' ')
 
    parser.add_option('-o', '--output-delimiter',
                      action = 'store',
                      type = 'string',
                      dest = 'outputDelimiter',
                      default = ' ')
 
    options, args = parser.parse_args(argv[1:])
 
    return options
 
 
def main() :
    options = parseOptions(argv)
    # Get input.
    lines = []
 
    try :
        line = raw_input()
    except EOFError :
        return
 
    while True:
        lines.append(line)
        try :
            line = raw_input()
        except EOFError :
            break
    
    formattedLines = formatter(lines,
                               options.inputDelimiter,
                               options.outputDelimiter)
 
    for line in formattedLines :
        print line
 
if __name__ == '__main__' :
    main()