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_): # match word
39
                in_ = (r'(?:^|(?<=[\s,"])|^:|(?<=[\s,"]):)'+re.escape(in_)
40
                    +r'(?![^\W_.-])')
41
            repls.append((r'(?m)'+in_, out))
42
    stream.close()
43
    def repl_all(str_):
44
        for repl, with_ in repls: str_ = re.sub(repl, with_, str_)
45
        return str_
46
    
47
    # Modify map or file
48
    if col_num != None:
49
        reader = csv.reader(sys.stdin)
50
        writer = csv.writer(sys.stdout)
51
        cols = reader.next()
52
        writer.writerow(cols)
53
        for row in reader:
54
            row[col_num] = repl_all(row[col_num])
55
            writer.writerow(row)
56
    else: sys.stdout.write(repl_all(sys.stdin.read()))
57

    
58
main()
(56-56/73)