Project

General

Profile

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