Project

General

Profile

1
#!/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
import util
12

    
13
def main():
14
    try: _prog_name, map_1_path = sys.argv[:2]
15
    except ValueError:
16
        raise SystemExit('Usage: '+sys.argv[0]+' <map_0 map_1 '
17
            '[compare_col_num...] [| '+sys.argv[0]
18
            +' map_2]... >intersect_map')
19
    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
    
23
    def compare_on(row): return tuple(util.list_subset(row, compare_col_nums))
24
    
25
    headers = [None]*2
26
    
27
    # Get map 1
28
    compare_cols = set()
29
    stream = open(map_1_path, 'rb')
30
    reader = csv.reader(stream)
31
    headers[1] = reader.next()
32
    for row in reader:
33
        if row[0] != '':
34
            compare_cols.add(compare_on(row))
35
    stream.close()
36
    
37
    # Open map 0
38
    reader = csv.reader(sys.stdin)
39
    headers[0] = reader.next()
40
    
41
    # 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
    # Add map 0 to map 1, overwriting existing entries
48
    writer = csv.writer(sys.stdout)
49
    writer.writerow(headers[0])
50
    for row in reader:
51
        if not combinable or compare_on(row) in compare_cols:
52
            # not combinable, or in map 1
53
            writer.writerow(row)
54

    
55
main()
(20-20/46)