File: ReplaceValues.py

package info (click to toggle)
lyx 2.5.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 138,444 kB
  • sloc: cpp: 244,268; ansic: 106,398; xml: 72,791; python: 39,384; sh: 7,666; makefile: 6,584; pascal: 2,143; perl: 2,101; objc: 1,084; tcl: 163; sed: 16
file content (58 lines) | stat: -rwxr-xr-x 1,626 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#! /usr/bin/python3

from __future__ import print_function

# file ReplaceValues.py
#
# This file is part of LyX, the document processor.
# Licence details can be found in the file COPYING.
#
# author: Kornel Benko, kornel@lyx.org
#
# Syntax: ReplaceValues.py [<var1>=<Subst1> [<var2>=<Subst> ...]] <Inputfile> [<Inputfile> ...]

import sys
import re
import codecs

Subst = {}  # map of desired substitutions
prog = re.compile("")

def createProg():
    matchingS = u"\\b|\\b".join(Subst.keys())
    pattern = u"".join(["(.*)(\\b", matchingS, "\\b)(.*)"])
    return re.compile(pattern)

def SubstituteDataInLine(line):
    m = prog.match(line)
    if m:
        return "".join([SubstituteDataInLine(m.group(1)),
                        Subst[m.group(2)],
                        SubstituteDataInLine(m.group(3))])
    return line


def SubstituteDataInFile(InFile):
    for line in codecs.open(InFile, 'r', 'UTF-8'):
        print(SubstituteDataInLine(line[:-1]))

##########################################

# ensure standard output with UTF8 encoding:
if sys.version_info < (3,0):
    sys.stdout = codecs.getwriter('UTF-8')(sys.stdout)
else:
    sys.stdout = codecs.getwriter('UTF-8')(sys.stdout.buffer)

for arg in sys.argv[1:]:         # skip first arg (name of this script)
    if sys.version_info < (3,0):
        # support non-ASCII characters in arguments
        arg = arg.decode(sys.stdin.encoding or 'UTF-8')
    entry = arg.split("=", 1)
    if len(entry) == 2:
        key, val = entry
        if len(key) > 0:
            Subst[key] = val
    else:
        prog = createProg()
        SubstituteDataInFile(arg)