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 9785 aaronmk
import HTMLParser
7 1705 aaronmk
import os.path
8 205 aaronmk
import re
9
import sys
10
11 1705 aaronmk
sys.path.append(os.path.dirname(__file__)+"/../lib")
12
13
import maps
14 4357 aaronmk
import opts
15 9784 aaronmk
import strings
16 1705 aaronmk
17 10348 aaronmk
quote_re = '[\'"`]'
18
19 9785 aaronmk
def unescape_html(str_): return HTMLParser.HTMLParser().unescape(str_)
20
21
def repl_unescape_html(match): return unescape_html(match.group(0))
22
23 205 aaronmk
def main():
24 4357 aaronmk
    env_names = []
25
    def usage_err():
26
        raise SystemExit('Usage: '+opts.env_usage(env_names, True)+' '
27
            +sys.argv[0]+' <map repl [col_num] [| '+sys.argv[0]
28
            +' repl_1 [col_num_1]]... >new_map')
29
30
    text = opts.env_flag('text', False, env_names) # all patterns are plain text
31 205 aaronmk
    try: _prog_name, repl_path = sys.argv[:2]
32 4357 aaronmk
    except ValueError: usage_err()
33 205 aaronmk
    col_num = None
34
    try: col_num = sys.argv[2]
35 211 aaronmk
    except IndexError: pass
36 205 aaronmk
    if col_num != None: col_num = int(col_num) # 0-based
37
38
    # Get replacements
39
    repls = []
40
    stream = open(repl_path, 'rb')
41
    reader = csv.reader(stream)
42 8740 aaronmk
    reader.next() # skip header
43 205 aaronmk
    for row in reader:
44 210 aaronmk
        in_, out = row[:2]
45 216 aaronmk
        if in_ != '':
46 10348 aaronmk
            is_word = re.match(r'^\w+$', in_)
47
            if text or is_word: # match as whole-word text (like SQL identifier)
48
                in_str_re = re.escape(in_)
49
                q = quote_re
50
                in_ = '(?<='+q+')'+in_str_re+'(?='+q+')' # require quotes
51 12742 aaronmk
                if is_word: # also match with quotes optional
52
                    in_word_re = r'\b'+in_str_re+r'(?=\b|_)' # also w/ suffix
53 10348 aaronmk
                    in_ = '(?:'+in_+'|'+in_word_re+')'
54 6713 aaronmk
            repls.append((r'(?m)'+in_, out))
55 205 aaronmk
    stream.close()
56
    def repl_all(str_):
57 9784 aaronmk
        str_ = strings.ustr(str_)
58 9785 aaronmk
        for repl, with_ in repls:
59
            if with_ == 'unescape_html()': with_ = repl_unescape_html
60
            str_ = re.sub(repl, with_, str_)
61 205 aaronmk
        return str_
62
63
    # Modify map or file
64
    if col_num != None:
65
        reader = csv.reader(sys.stdin)
66
        writer = csv.writer(sys.stdout)
67
        cols = reader.next()
68
        writer.writerow(cols)
69
        for row in reader:
70
            row[col_num] = repl_all(row[col_num])
71
            writer.writerow(row)
72 9784 aaronmk
    else: sys.stdout.write(strings.to_raw_str(repl_all(sys.stdin.read())))
73 205 aaronmk
74
main()