Aug-06-2021, 09:13 PM
(Aug-06-2021, 09:05 PM)bowlofred Wrote: If it's not too huge, I'd just loop over it. But for very large files, that's inefficient.
paragraph = """This example is an example on how to make an example with the word example. the example ends here with an example. for example""" target = "example" counter = 0 while target in paragraph: counter += 1 paragraph = paragraph.replace(target, str(counter), 1) print(paragraph)If it is huge, time to break out regex parser. I think there should be a simpler way to write a callable incrementor, but this will do for now.
import re target = "example" def str_counter(match_object): str_counter.count += 1 return str(str_counter.count) str_counter.count = 0 paragraph = """This example is an example on how to make an example with the word example. the example ends here with an example. for example""" paragraph = re.sub(re.escape(target), str_counter, paragraph) print(paragraph)
Hey, thanks for replying.
Where do I have to define that my script should check in text-files? And what's the difference between target and paragraph?