1
|
#!/usr/bin/env python
|
2
|
# Inner-joins two map spreadsheets A->B and B->C to A->C
|
3
|
|
4
|
import csv
|
5
|
import os.path
|
6
|
import sys
|
7
|
import warnings
|
8
|
|
9
|
sys.path.append(os.path.dirname(__file__)+"/../lib")
|
10
|
|
11
|
import maps
|
12
|
import util
|
13
|
|
14
|
def main():
|
15
|
try: _prog_name, map_1_path = sys.argv
|
16
|
except ValueError:
|
17
|
raise SystemExit('Usage: '+sys.argv[0]+' <map_0 map_1 [| '+sys.argv[0]
|
18
|
+' map_2]... >joined_map')
|
19
|
|
20
|
# Get map 1
|
21
|
map_1 = {}
|
22
|
stream = open(map_1_path, 'rb')
|
23
|
reader = csv.reader(stream)
|
24
|
map_1_cols = reader.next()
|
25
|
for row in reader:
|
26
|
if row[0] != '': map_1[row[0]] = row
|
27
|
stream.close()
|
28
|
|
29
|
# Join map 1 to map 0
|
30
|
reader = csv.reader(sys.stdin)
|
31
|
writer = csv.writer(sys.stdout)
|
32
|
map_0_cols = reader.next()
|
33
|
if not map_0_cols[1] == map_1_cols[0]: raise SystemExit('Map error: '
|
34
|
'Map 0 output column name doesn\'t match map 1 input column name')
|
35
|
writer.writerow(maps.merge_mappings(map_0_cols, map_1_cols))
|
36
|
for row in reader:
|
37
|
if row[1] != '':
|
38
|
# Look for a match
|
39
|
out_row = None
|
40
|
suffix = ''
|
41
|
while True:
|
42
|
try:
|
43
|
out_row = map_1[row[1]]
|
44
|
break
|
45
|
except KeyError:
|
46
|
# Heuristically look for a match on a parent path.
|
47
|
# If this produces a syntactically invalid parent path (e.g.
|
48
|
# there is a / within []), it will be ignored since there
|
49
|
# wouldn't be a an entry in map_1.
|
50
|
row[1], sep, new_suffix = row[1].rpartition('/')
|
51
|
if sep == '': break
|
52
|
suffix = sep+new_suffix+suffix # prepend new suffix
|
53
|
|
54
|
# Write new mapping
|
55
|
if out_row != None:
|
56
|
row = maps.merge_mappings(row, out_row)
|
57
|
row[1] += suffix # don't modify out_row!
|
58
|
else:
|
59
|
msg = 'No join mapping for '+row[1]
|
60
|
warnings.warn(UserWarning(msg))
|
61
|
row[2] = '** '+msg+' ** '+util.list_setdefault(row, 2, '')
|
62
|
row[1] = ''
|
63
|
writer.writerow(row)
|
64
|
|
65
|
main()
|