Project

General

Profile

1 927 aaronmk
#!/usr/bin/env python
2
# Intersects two map spreadsheets A0->B and A1->C to A->B, with B overwriting C
3
4
import csv
5
import os.path
6
import sys
7
8
sys.path.append(os.path.dirname(__file__)+"/../lib")
9
10
import maps
11 1525 aaronmk
import util
12 927 aaronmk
13
def main():
14 1525 aaronmk
    try: _prog_name, map_1_path = sys.argv[:2]
15 927 aaronmk
    except ValueError:
16 1525 aaronmk
        raise SystemExit('Usage: '+sys.argv[0]+' <map_0 map_1 '
17
            '[compare_col_num...] [| '+sys.argv[0]
18 927 aaronmk
            +' map_2]... >intersect_map')
19 1525 aaronmk
    compare_col_nums = map(int, sys.argv[2:]) # 0-based
20
    if compare_col_nums == []:
21
        compare_col_nums = None # list_subset() value for all columns
22 927 aaronmk
23 1525 aaronmk
    def compare_on(row): return tuple(util.list_subset(row, compare_col_nums))
24
25
    headers = [None]*2
26
27 927 aaronmk
    # Get map 1
28 1525 aaronmk
    compare_cols = set()
29 927 aaronmk
    stream = open(map_1_path, 'rb')
30
    reader = csv.reader(stream)
31 1525 aaronmk
    headers[1] = reader.next()
32 927 aaronmk
    for row in reader:
33 1525 aaronmk
        if row[0] != '':
34
            compare_cols.add(compare_on(row))
35 927 aaronmk
    stream.close()
36
37
    # Open map 0
38
    reader = csv.reader(sys.stdin)
39 1525 aaronmk
    headers[0] = reader.next()
40 927 aaronmk
41 1525 aaronmk
    # Check col labels
42
    combinable = maps.combinable(*headers)
43
    if not combinable and not ignore:
44
        raise SystemExit('Map error: '
45
        'Map 0 column 0 label doesn\'t contain map 1 column 0 label')
46
47 927 aaronmk
    # Add map 0 to map 1, overwriting existing entries
48
    writer = csv.writer(sys.stdout)
49 1525 aaronmk
    writer.writerow(headers[0])
50 927 aaronmk
    for row in reader:
51 1525 aaronmk
        if not combinable or compare_on(row) in compare_cols:
52
            # not combinable, or in map 1
53
            writer.writerow(row)
54 927 aaronmk
55
main()