Project

General

Profile

1 205 aaronmk
#!/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 1705 aaronmk
import os.path
7 205 aaronmk
import re
8
import sys
9
10 1705 aaronmk
sys.path.append(os.path.dirname(__file__)+"/../lib")
11
12
import maps
13 4357 aaronmk
import opts
14 9784 aaronmk
import strings
15 1705 aaronmk
16 205 aaronmk
def main():
17 4357 aaronmk
    env_names = []
18
    def usage_err():
19
        raise SystemExit('Usage: '+opts.env_usage(env_names, True)+' '
20
            +sys.argv[0]+' <map repl [col_num] [| '+sys.argv[0]
21
            +' repl_1 [col_num_1]]... >new_map')
22
23
    text = opts.env_flag('text', False, env_names) # all patterns are plain text
24 205 aaronmk
    try: _prog_name, repl_path = sys.argv[:2]
25 4357 aaronmk
    except ValueError: usage_err()
26 205 aaronmk
    col_num = None
27
    try: col_num = sys.argv[2]
28 211 aaronmk
    except IndexError: pass
29 205 aaronmk
    if col_num != None: col_num = int(col_num) # 0-based
30
31
    # Get replacements
32
    repls = []
33
    stream = open(repl_path, 'rb')
34
    reader = csv.reader(stream)
35 8740 aaronmk
    reader.next() # skip header
36 205 aaronmk
    for row in reader:
37 210 aaronmk
        in_, out = row[:2]
38 216 aaronmk
        if in_ != '':
39 6702 aaronmk
            if text or re.match(r'^\w+$', in_): # match word
40 6713 aaronmk
                in_ = (r'(?:^|(?<=[\s,"])|^:|(?<=[\s,"]):)'+re.escape(in_)
41
                    +r'(?![^\W_.-])')
42
            repls.append((r'(?m)'+in_, out))
43 205 aaronmk
    stream.close()
44
    def repl_all(str_):
45 9784 aaronmk
        str_ = strings.ustr(str_)
46 205 aaronmk
        for repl, with_ in repls: str_ = re.sub(repl, with_, str_)
47
        return str_
48
49
    # Modify map or file
50
    if col_num != None:
51
        reader = csv.reader(sys.stdin)
52
        writer = csv.writer(sys.stdout)
53
        cols = reader.next()
54
        writer.writerow(cols)
55
        for row in reader:
56
            row[col_num] = repl_all(row[col_num])
57
            writer.writerow(row)
58 9784 aaronmk
    else: sys.stdout.write(strings.to_raw_str(repl_all(sys.stdin.read())))
59 205 aaronmk
60
main()