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
| from odf import opendocument, text, teletype
from odf.text import P
from odf.style import Style, TextProperties, ParagraphProperties
doc = opendocument.load(r"C:\Users\chris\Documents\mesScryptPython\fichiers odt\mon second document.odt")
def saxiter(Element1): #-> Iterator[Element]:
"""Return an interator over all elements reachable from node: later siblings and recursively all children."""
while node:
yield node
if node.hasChildNodes():
yield from saxiter(node.firstChild)
node = node.nextSibling
def edittextElements(doc, pattern): #-> Generator[tuple[str, str], str, None]:
"""Goes over all elements, and look for the text that contains the given."""
for elem in saxiter(doc.topnode):
if elem.__class__ is Text:
for pat in pattern:
if pat in str(elem):
elem.data = yield (pat, elem.data)
patterns = ["code"]
gen = edittextElements(doc, patterns)
try:
while True:
pat, old_text = next(gen)
new_text = old_text.replace(pat, "to this")
gen.send(new_text)
print(gen.send(new_text))
except StopIteration:
pass
try:
while True:
pat, old_text = next(gen)
new_text = old_text.replace('code', "to this")
gen.send(new_text)
doc.save(r"C:\Users\chris\Documents\mesScryptPython\fichiers odt\mon second document3.odt")
except StopIteration:
pass |
Partager