1 |
157
|
aaronmk
|
#!/usr/bin/env python
|
2 |
|
|
# Sorts a spreadsheet based on a column
|
3 |
|
|
|
4 |
|
|
import csv
|
5 |
|
|
import sys
|
6 |
|
|
|
7 |
189
|
aaronmk
|
def by_idx(list_, idxes): return [list_[i] for i in idxes]
|
8 |
|
|
|
9 |
727
|
aaronmk
|
def cmp_nulls_last(*row_pair):
|
10 |
|
|
def repl(val):
|
11 |
|
|
if val == '': val = () # sorts > ''
|
12 |
|
|
return val
|
13 |
|
|
return cmp(*map(lambda row: map(repl, row), row_pair))
|
14 |
|
|
|
15 |
157
|
aaronmk
|
def main():
|
16 |
189
|
aaronmk
|
col_nums = sys.argv[1:]
|
17 |
|
|
if col_nums == []:
|
18 |
|
|
raise SystemExit('Usage: '+sys.argv[0]+' col_num... <map >sorted_map')
|
19 |
|
|
col_nums = map(int, col_nums) # 0-based
|
20 |
157
|
aaronmk
|
|
21 |
|
|
# Sort map
|
22 |
|
|
reader = csv.reader(sys.stdin)
|
23 |
|
|
cols = reader.next()
|
24 |
189
|
aaronmk
|
def get_sort_by(row): return by_idx(row, col_nums)
|
25 |
157
|
aaronmk
|
rows = list(reader)
|
26 |
727
|
aaronmk
|
rows.sort(lambda *row_pair: cmp_nulls_last(*map(get_sort_by, row_pair)))
|
27 |
157
|
aaronmk
|
writer = csv.writer(sys.stdout)
|
28 |
|
|
writer.writerow(cols)
|
29 |
|
|
map(writer.writerow, rows)
|
30 |
|
|
|
31 |
|
|
main()
|