1 |
51
|
aaronmk
|
#!/usr/bin/env python
|
2 |
|
|
# Inner-joins two map spreadsheets A->B and B->C to A->C
|
3 |
|
|
|
4 |
|
|
import csv
|
5 |
|
|
import sys
|
6 |
|
|
|
7 |
|
|
def main():
|
8 |
67
|
aaronmk
|
try: _prog_name, map_1_path = sys.argv
|
9 |
51
|
aaronmk
|
except ValueError:
|
10 |
67
|
aaronmk
|
raise SystemExit('Usage: '+sys.argv[0]+' map_1 <map_0 >joined_map')
|
11 |
51
|
aaronmk
|
|
12 |
|
|
# Get map 1
|
13 |
|
|
map_1 = {}
|
14 |
|
|
stream = open(map_1_path, 'rb')
|
15 |
59
|
aaronmk
|
reader = csv.reader(stream)
|
16 |
51
|
aaronmk
|
map_1_in, map_1_out = reader.next()[:2]
|
17 |
|
|
for row in reader:
|
18 |
|
|
if row[1] != '': map_1[row[0]] = row[1]
|
19 |
|
|
stream.close()
|
20 |
|
|
|
21 |
|
|
# Join map 1 to map 0
|
22 |
59
|
aaronmk
|
reader = csv.reader(sys.stdin)
|
23 |
120
|
aaronmk
|
writer = csv.writer(sys.stdout)
|
24 |
|
|
cols = reader.next()
|
25 |
|
|
if not cols[1] == map_1_in: raise SystemExit( 'Map error: '
|
26 |
62
|
aaronmk
|
'Map 0 output column name doesn\'t match map 1 input column name')
|
27 |
120
|
aaronmk
|
cols[1] = map_1_out
|
28 |
|
|
writer.writerow(cols)
|
29 |
51
|
aaronmk
|
for row in reader:
|
30 |
120
|
aaronmk
|
try: row[1] = map_1[row[1]]
|
31 |
|
|
except KeyError: continue # skip row
|
32 |
|
|
writer.writerow(row)
|
33 |
51
|
aaronmk
|
|
34 |
|
|
main()
|