File: replacer.py

package info (click to toggle)
cp2k 2025.2-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 372,060 kB
  • sloc: fortran: 963,262; ansic: 64,495; f90: 21,676; python: 14,419; sh: 11,382; xml: 2,173; makefile: 996; pascal: 845; perl: 492; cpp: 345; lisp: 297; csh: 16
file content (38 lines) | stat: -rw-r--r-- 1,116 bytes parent folder | download | duplicates (4)
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
#!/usr/bin/env python3

import re
import sys

repl = {"routine_name": "routineN", "module_name": "moduleN"}
specialRepl = None
# { re.compile(r"(.*:: *moduleN) *= *(['\"])[a-zA-Z_0-9]+\2",flags=re.IGNORECASE):r"character(len=*), parameter :: moduleN = '__MODULE_NAME__'" }


def replaceWords(infile, outfile, replacements=repl, specialReplacements=specialRepl):
    """Replaces the words in infile writing the output to outfile.

    replacements is a dictionary with the words to replace.
    specialReplacements is a dictionary with general regexp replacements.
    """
    lineNr = 0
    nonWordRe = re.compile(r"(\W+)")

    while 1:
        line = infile.readline()
        lineNr = lineNr + 1
        if not line:
            break

        if specialReplacements:
            for subs in specialReplacements.keys():
                line = subs.sub(specialReplacements[subs], line)

        tokens = nonWordRe.split(line)
        for token in tokens:
            if token in replacements.keys():
                outfile.write(replacements[token])
            else:
                outfile.write(token)


# EOF