Project

General

Profile

1
#!/usr/bin/env python
2
# Modifies a map spreadsheet A->B or any file using a replacements spreadsheet
3
# A->C or B->C
4

    
5
import csv
6
import os.path
7
import re
8
import sys
9

    
10
sys.path.append(os.path.dirname(__file__)+"/../lib")
11

    
12
import maps
13
import opts
14

    
15
def main():
16
    env_names = []
17
    def usage_err():
18
        raise SystemExit('Usage: '+opts.env_usage(env_names, True)+' '
19
            +sys.argv[0]+' <map repl [col_num] [| '+sys.argv[0]
20
            +' repl_1 [col_num_1]]... >new_map')
21
    
22
    text = opts.env_flag('text', False, env_names) # all patterns are plain text
23
    try: _prog_name, repl_path = sys.argv[:2]
24
    except ValueError: usage_err()
25
    col_num = None
26
    try: col_num = sys.argv[2]
27
    except IndexError: pass
28
    if col_num != None: col_num = int(col_num) # 0-based
29
    
30
    # Get replacements
31
    repls = []
32
    stream = open(repl_path, 'rb')
33
    reader = csv.reader(stream)
34
    repl_in, repl_out = reader.next()[:2]
35
    for row in reader:
36
        in_, out = row[:2]
37
        if in_ != '':
38
            if text or re.match(r'^\w+$', in_):
39
                in_ = r'(?<![^\W_])'+re.escape(in_)+r'(?![^\W_])' # match word
40
            repls.append((r'(?m)'+in_, out))
41
    stream.close()
42
    def repl_all(str_):
43
        for repl, with_ in repls: str_ = re.sub(repl, with_, str_)
44
        return str_
45
    
46
    # Modify map or file
47
    if col_num != None:
48
        reader = csv.reader(sys.stdin)
49
        writer = csv.writer(sys.stdout)
50
        cols = reader.next()
51
        label, root = maps.col_info(cols[col_num])[:2]
52
        if label != repl_in: raise SystemExit('Map error: Map column '+
53
            str(col_num)+' label "'+label+'" doesn\'t match replacements input '
54
            'column label "'+repl_in+'"')
55
        cols[col_num] = repl_out+sep+repl_all(root)
56
        writer.writerow(cols)
57
        for row in reader:
58
            row[col_num] = repl_all(row[col_num])
59
            writer.writerow(row)
60
    else: sys.stdout.write(repl_all(sys.stdin.read()))
61

    
62
main()
(49-49/66)