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 |
180
|
aaronmk
|
raise SystemExit('Usage: '+sys.argv[0]+' <map_0 map_1 [| '+sys.argv[0]
|
11 |
|
|
+' map_2]... >joined_map')
|
12 |
51
|
aaronmk
|
|
13 |
|
|
# Get map 1
|
14 |
|
|
map_1 = {}
|
15 |
|
|
stream = open(map_1_path, 'rb')
|
16 |
59
|
aaronmk
|
reader = csv.reader(stream)
|
17 |
51
|
aaronmk
|
map_1_in, map_1_out = reader.next()[:2]
|
18 |
|
|
for row in reader:
|
19 |
|
|
if row[1] != '': map_1[row[0]] = row[1]
|
20 |
|
|
stream.close()
|
21 |
|
|
|
22 |
|
|
# Join map 1 to map 0
|
23 |
59
|
aaronmk
|
reader = csv.reader(sys.stdin)
|
24 |
120
|
aaronmk
|
writer = csv.writer(sys.stdout)
|
25 |
|
|
cols = reader.next()
|
26 |
177
|
aaronmk
|
if not cols[1] == map_1_in: raise SystemExit('Map error: '
|
27 |
62
|
aaronmk
|
'Map 0 output column name doesn\'t match map 1 input column name')
|
28 |
120
|
aaronmk
|
cols[1] = map_1_out
|
29 |
|
|
writer.writerow(cols)
|
30 |
51
|
aaronmk
|
for row in reader:
|
31 |
120
|
aaronmk
|
try: row[1] = map_1[row[1]]
|
32 |
|
|
except KeyError: continue # skip row
|
33 |
|
|
writer.writerow(row)
|
34 |
51
|
aaronmk
|
|
35 |
|
|
main()
|