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 |
734
|
aaronmk
|
import os.path
|
6 |
51
|
aaronmk
|
import sys
|
7 |
|
|
|
8 |
734
|
aaronmk
|
sys.path.append(os.path.dirname(__file__)+"/../lib")
|
9 |
732
|
aaronmk
|
|
10 |
734
|
aaronmk
|
import maps
|
11 |
|
|
|
12 |
51
|
aaronmk
|
def main():
|
13 |
67
|
aaronmk
|
try: _prog_name, map_1_path = sys.argv
|
14 |
51
|
aaronmk
|
except ValueError:
|
15 |
180
|
aaronmk
|
raise SystemExit('Usage: '+sys.argv[0]+' <map_0 map_1 [| '+sys.argv[0]
|
16 |
|
|
+' map_2]... >joined_map')
|
17 |
51
|
aaronmk
|
|
18 |
|
|
# Get map 1
|
19 |
|
|
map_1 = {}
|
20 |
|
|
stream = open(map_1_path, 'rb')
|
21 |
59
|
aaronmk
|
reader = csv.reader(stream)
|
22 |
737
|
aaronmk
|
map_1_cols = reader.next()
|
23 |
51
|
aaronmk
|
for row in reader:
|
24 |
732
|
aaronmk
|
if row[0] != '': map_1[row[0]] = row
|
25 |
51
|
aaronmk
|
stream.close()
|
26 |
|
|
|
27 |
|
|
# Join map 1 to map 0
|
28 |
59
|
aaronmk
|
reader = csv.reader(sys.stdin)
|
29 |
120
|
aaronmk
|
writer = csv.writer(sys.stdout)
|
30 |
737
|
aaronmk
|
map_0_cols = reader.next()
|
31 |
|
|
if not map_0_cols[1] == map_1_cols[0]: raise SystemExit('Map error: '
|
32 |
62
|
aaronmk
|
'Map 0 output column name doesn\'t match map 1 input column name')
|
33 |
737
|
aaronmk
|
writer.writerow(maps.merge_mappings(map_0_cols, map_1_cols))
|
34 |
51
|
aaronmk
|
for row in reader:
|
35 |
730
|
aaronmk
|
if row[1] != '':
|
36 |
735
|
aaronmk
|
try: out_row = map_1[row[1]]
|
37 |
730
|
aaronmk
|
except KeyError:
|
38 |
|
|
row[2] = '** No join mapping for '+row[1]+' ** '+row[2]
|
39 |
|
|
row[1] = ''
|
40 |
735
|
aaronmk
|
else: row = maps.merge_mappings(row, out_row)
|
41 |
120
|
aaronmk
|
writer.writerow(row)
|
42 |
51
|
aaronmk
|
|
43 |
|
|
main()
|