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,"]))(:?)'+re.escape(in_)+r'(?![^\W_.-])'
|
40
|
repls.append((r'(?m)'+in_, r'\1'+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
|
writer.writerow(cols)
|
52
|
for row in reader:
|
53
|
row[col_num] = repl_all(row[col_num])
|
54
|
writer.writerow(row)
|
55
|
else: sys.stdout.write(repl_all(sys.stdin.read()))
|
56
|
|
57
|
main()
|