Find, preview and replace text
"""Read-only preview, literal replacement, and regex replacement."""
from pathlib import Path
from pywpdoc import Document
def run(fmt: str, out_dir: Path) -> Path:
out_dir.mkdir(parents=True, exist_ok=True)
doc = Document.new(fmt)
doc.add_paragraph("Customer: Alice; Amount: 123")
preview = doc.preview_replace("Alice", "Bob")
assert preview.count == 1
assert "Alice" in doc.paragraphs[-1].text # preview never edits
assert doc.replace_text("Alice", "Bob") == 1
assert doc.replace_regex(r"\b123\b", "456") == 1
path = out_dir / f"search-replace.{fmt}"
doc.save(path)
assert "Bob" in Document.open(path).paragraphs[-1].text
return path
if __name__ == "__main__":
import sys
print(run(sys.argv[1], Path(sys.argv[2])))
Run: python examples/manual/search_replace.py hwpx ./output (also docx).
| Method | Return | Mutates document? |
|---|---|---|
find(query, *, everywhere=True, case_sensitive=True, count=-1) |
list of matches | No |
preview_replace(search, replacement, *, everywhere=True, case_sensitive=True, count=-1) |
ReplacementPreviewReport |
No |
replace_text(search, replacement, *, everywhere=True, case_sensitive=True, count=-1) |
number replaced (int) |
Yes |
find_regex(pattern, *, everywhere=True, flags=0, count=-1) |
matches | No |
replace_regex(pattern, replacement, *, everywhere=True, flags=0, count=-1) |
number replaced (int) |
Yes |
everywhere=False limits traversal to the scope defined by the text feature; do not assume it searches all headers and nested tables. Unsafe field/revision boundaries and empty-length regex matches may be rejected. Preview offsets are logical text positions, not screen coordinates. See results and errors.