-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsumcolumns
executable file
·79 lines (68 loc) · 2.36 KB
/
sumcolumns
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
#!/usr/bin/env python
# a quick command-line program for adding up numbers across columns
# Author: David McClosky
# Homepage: http://zorglish.org
# Code: http://github.com/dmcc
import sys
import re
import optparse
from waterworks.Strings import try_parse_float
from AIMA import vector_add
parser = optparse.OptionParser()
parser.add_option('-t', '--table', action='store_true',
help='Show parsed data as a table (for sanity checking)')
parser.add_option('-c', '--cumulative', action='store_true',
help='Show cumulative percentiles')
parser.add_option('-p', '--percentages', action='store_true',
help='Show non-cumulative percentages')
opts, args = parser.parse_args()
not_numbers_re = re.compile(r'[^0-9\.]')
def cleanup(cell):
numbers_only = not_numbers_re.sub('', cell)
return try_parse_float(numbers_only, 0)
lines = sys.stdin.readlines()
totals = None
if opts.table:
import texttable
table = texttable.Texttable()
table.set_deco(table.BORDER)
rows = []
for line in lines:
row = [cleanup(cell) for cell in line.split()]
if opts.table:
rows.append(row)
if totals is None:
totals = row
else:
assert len(row) == len(totals)
totals = vector_add(totals, row)
if opts.table:
table.set_cols_align(['r'] * len(totals))
rows.append(['---'] * len(totals))
rows.append(totals)
table.add_rows(rows)
print(table.draw())
if opts.cumulative:
cumulative_total = None
print('--- Cumulative totals ---')
for line in lines:
row = [cleanup(cell) for cell in line.split()]
if cumulative_total is None:
cumulative_total = row
else:
cumulative_total = vector_add(cumulative_total, row)
cumulative = ["%.1f%%" % (100 * i / j)
for i, j in zip(cumulative_total, totals)
if j != 0]
print(line.rstrip(), '|', ' '.join(cumulative))
print('---')
elif opts.percentages:
print('--- Percentages ---')
for line in lines:
row = [cleanup(cell) for cell in line.split()]
percentages = ["%.1f%%" % (100 * i / j)
for i, j in zip(row, totals)
if j != 0]
print(line.rstrip(), '|', ' '.join(percentages))
print('---')
print('Total(s):', ' '.join(str(total) for total in totals if total > 0))