From 7db0258b5c49be554bface11249fa6c296f3348b Mon Sep 17 00:00:00 2001 From: Bjoern Brandenburg Date: Thu, 4 Sep 2008 22:36:50 -0400 Subject: teach csv_tool to reorder columns --- csv_tool | 25 ++++++++++++++++++++++--- 1 file changed, 22 insertions(+), 3 deletions(-) diff --git a/csv_tool b/csv_tool index 10f5ee0..674c51c 100755 --- a/csv_tool +++ b/csv_tool @@ -15,8 +15,9 @@ o = optparse.make_option opts = [ -# o('-t', '--two', action='store', dest='double_val', nargs=2, type='int', -# help='A two-parameter option.'), + o('-x', '--exchange', action='append', dest='col_xchg', + nargs=2, type='int', + help='Columns that should be switched with reorder.'), o('-c', '--column', action='store', dest='col', type='int', help='The column on which to operate.'), @@ -30,6 +31,7 @@ opts = [ defaults = { 'col' : 0, + 'col_xcgh' : [], } def make_vector_op(op): @@ -84,6 +86,14 @@ def transpose(rows): for i in xrange(c): yield [at(j, i) for j in xrange(r) ] + +def reorder_columns(rows, xchg_pairs): + for r in rows: + print type(r) + for (x,y) in xchg_pairs: + r[x], r[y] = r[y], r[x] + yield r + def select_by_key(rows, col, cast=None): by_key = defdict(list) order = [] @@ -99,6 +109,9 @@ def select_by_key(rows, col, cast=None): class CsvApp(defapp.App): def __init__(self): defapp.App.__init__(self, opts, defaults) + self.options.col -= 1 + self.options.col_xchg = [(x - 1, y - 1) for (x, y) in + self.options.col_xchg] def transform(self, make_iterator, ordered=True): """Average all rows with the same key in a given column.""" @@ -110,7 +123,8 @@ class CsvApp(defapp.App): rows = csv.reader(open(fn, 'r')) # set up transformation if ordered: - (order, by_key) = select_by_key(rows, self.options.col, float) + (order, by_key) = select_by_key(rows, self.options.col, + float) rows = make_iterator(order, by_key) else: rows = make_iterator(rows) @@ -137,5 +151,10 @@ class CsvApp(defapp.App): def do_transpose(self, _): self.transform(transpose, ordered=False) + def do_reorder(self, _): + self.transform(lambda rows: reorder_columns(rows, + self.options.col_xchg), + ordered=False) + if __name__ == '__main__': CsvApp().launch() -- cgit v1.2.2