Created
July 20, 2023 05:16
-
-
Save MonoidMusician/7445b0e216da201a0bea51ae8b351d1e to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
import re | |
import sys | |
# install this dependency from pip: | |
from wrapt import ObjectProxy | |
class FormattableMatch(ObjectProxy): | |
def __str__(self): | |
m = self.__wrapped__ | |
if "m" in m.groupdict(): | |
return m["m"] | |
return m[0] | |
def target(tgt, fn, data): | |
print(list(tgt.finditer(data))) | |
return tgt.subn | |
def process(m): | |
v = dict() | |
coes = dict((cls.__name__, cls) for cls in [int, float, str]) | |
for (index, value) in enumerate(m.groups()): | |
v[index] = value | |
for name in m.groupdict().keys(): | |
index = m.re.groupindex[name] | |
value = m[index] | |
for coe in coes: | |
if name.startswith(coe): | |
value = coes[coe](value) | |
v[name] = value | |
v[index] = value | |
return {"v":v,**v,"m":FormattableMatch(m)} | |
# https://python-forum.io/thread-24481.html | |
def fstring(f, *arg): | |
return eval(f'f{f!r}', None, *arg) | |
def set_span(m, span, r): | |
z = m.start() | |
s = m[0] | |
if type(span) == str: | |
span = m.span(span) | |
if type(span) == re.Match: | |
span = span.span(0) | |
return s[:span[0] - z] + r + s[span[1] - z:] | |
def run(cmd, m): | |
r = fstring(cmd, process(m)) | |
if "m" in m.groupdict(): | |
r = set_span(m, "m", r) | |
return r | |
predefs = { | |
"$ratio": ( | |
# {ratio,1,2} | |
"""{ratio,(?P<m>(?P<intN>-?[0-9]+),(?P<intD>[0-9]+))}""", | |
# {ratio,1,2,0.5} | |
"""{m},{intN / intD}""" | |
), | |
"$unratio": ( | |
# {ratio,1,2} | |
"""{ratio,(?P<intN>-?[0-9]+),(?P<intD>[0-9]+)}""", | |
# 0.5 | |
"""{intN / intD}""" | |
), | |
} | |
if __name__ == '__main__': | |
argv = sys.argv[1:] | |
steps = [] | |
while len(argv) and argv[0].startswith("$"): | |
steps.append(predefs[argv.pop(0)]) | |
if len(argv) >= 2: | |
steps.append((argv.pop(0), argv.pop(0))) | |
if len(argv): | |
data = "\n".join(argv) | |
else: | |
data = sys.stdin.read() | |
if len(data) and data[-1] == "\n": | |
data = data[:-1] | |
for (tgt, cmd) in steps: | |
data = re.sub(tgt, lambda m: run(cmd, m), data) | |
print(data) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment