Download scripts/block_edit.py from spark-school/school-corpus: direct link, hf CLI and curl.
- Browser
- Download file 1.73 kB
-
https://huggingface.co/datasets/spark-school/school-corpus/resolve/main/scripts/block_edit.py
- Command line
-
hf download hf://datasets/spark-school/school-corpus/scripts/block_edit.py
-
curl -L -o block_edit.py https://huggingface.co/datasets/spark-school/school-corpus/resolve/main/scripts/block_edit.py
1.73 kB
| """Block-scoped replace for multi-block stores (erosion pass 131 installation form). | |
| A replace inside a store of repeated blocks gets block scope: slice from the | |
| target header to the next header, replace inside the slice, reassemble. | |
| 'First match' in a global replace is a property of the file, not of your intent. | |
| """ | |
| import re | |
| def block_replace(path: str, header_prefix: str, old: str, new: str, | |
| header_re: str = r"^## ") -> dict: | |
| """Replace `old` with `new` ONLY inside the block that starts with the line | |
| beginning `header_prefix`. Returns {'ok': bool, 'replacements': int, 'why': str}.""" | |
| txt = open(path, encoding="utf-8").read() | |
| lines = txt.splitlines(keepends=True) | |
| # find target header (case-insensitive: store headers are mixed-case families) | |
| hi = None | |
| hp_low = header_prefix.lower() | |
| for i, l in enumerate(lines): | |
| if l.lower().startswith(hp_low): | |
| hi = i | |
| break | |
| if hi is None: | |
| return {"ok": False, "replacements": 0, "why": "target header not found"} | |
| # find next header after target | |
| nj = len(lines) | |
| for j in range(hi + 1, len(lines)): | |
| if re.match(header_re, lines[j]): | |
| nj = j | |
| break | |
| block = "".join(lines[hi:nj]) | |
| n = block.count(old) | |
| if n == 0: | |
| return {"ok": False, "replacements": 0, "why": "old string absent in target block"} | |
| if n > 1: | |
| return {"ok": False, "replacements": 0, "why": f"old string non-unique in block (n={n})"} | |
| block2 = block.replace(old, new) | |
| out = "".join(lines[:hi]) + block2 + "".join(lines[nj:]) | |
| open(path, "w", encoding="utf-8").write(out) | |
| return {"ok": True, "replacements": 1, "why": "replaced in block scope"} | |