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 HTMLParser
7
import os.path
8
import re
9
import sys
10

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

    
13
import maps
14
import opts
15
import strings
16

    
17
quote_re = '[\'"`]'
18
excluded_prefix_re = (
19
	'(?<!\*)' # don't double leading *
20
	)
21

    
22
def unescape_html(str_): return HTMLParser.HTMLParser().unescape(str_)
23

    
24
def repl_unescape_html(match): return unescape_html(match.group(0))
25

    
26
def main():
27
    env_names = []
28
    def usage_err():
29
        raise SystemExit('Usage: '+opts.env_usage(env_names, True)+' '
30
            +sys.argv[0]+' <map repl [col_num] [| '+sys.argv[0]
31
            +' repl_1 [col_num_1]]... >new_map')
32
    
33
    text = opts.env_flag('text', False, env_names) # all patterns are plain text
34
    try: _prog_name, repl_path = sys.argv[:2]
35
    except ValueError: usage_err()
36
    col_num = None
37
    try: col_num = sys.argv[2]
38
    except IndexError: pass
39
    if col_num != None: col_num = int(col_num) # 0-based
40
    
41
    # Get replacements
42
    repls = []
43
    stream = open(repl_path, 'rb')
44
    reader = csv.reader(stream)
45
    reader.next() # skip header
46
    for row in reader:
47
        in_, out = row[:2]
48
        if in_ != '':
49
            is_word = re.match(r'^\w+$', in_)
50
            if text or is_word: # match as whole-word text (like SQL identifier)
51
                in_str_re = re.escape(in_)
52
                q = quote_re
53
                in_ = '(?<='+q+')'+in_str_re+'(?='+q+')' # require quotes
54
                if is_word: # also match with quotes optional
55
                    in_word_re = excluded_prefix_re+r'\b'+in_str_re+r'(?=\b|_)'
56
                        # (?=\b|_): also match w/ _* suffix
57
                    in_ = '(?:'+in_+'|'+in_word_re+')'
58
            repls.append((r'(?m)'+in_, out))
59
    stream.close()
60
    def repl_all(str_):
61
        str_ = strings.ustr(str_)
62
        for repl, with_ in repls:
63
            if with_ == 'unescape_html()': with_ = repl_unescape_html
64
            str_ = re.sub(repl, with_, str_)
65
        return str_
66
    
67
    # Modify map or file
68
    if col_num != None:
69
        reader = csv.reader(sys.stdin)
70
        writer = csv.writer(sys.stdout)
71
        cols = reader.next()
72
        writer.writerow(cols)
73
        for row in reader:
74
            row[col_num] = repl_all(row[col_num])
75
            writer.writerow(row)
76
    else: sys.stdout.write(strings.to_raw_str(repl_all(sys.stdin.read())))
77

    
78
main()
(65-65/86)