Count and replacing strings a texfile

Fredrik Lundh fredrik at effbot.org
Mon Jan 22 18:14:03 EST 2001


pucko (?) wrote:
> This is a probably basic question.
> I have a textfile about 120k large, and there is several strings in it
> which I must replace.
> The strings are named "%id%" and the number of strings are unknown.
>
> First, I need to count them all.
> Then I must replace every one of them with a incrementing number.
> Like the first %id% is replaced with 1, the second with 2 etc.

how about:

import re

class Replacer:

    pattern = re.compile(r"%id%")

    def __init__(self):
        self.counter = 0

    def getcounter(self):
        return self.counter

    def fixup(self, m):
        self.counter = self.counter + 1
        return str(self.counter)

    def replace(self, text):
        return self.pattern.sub(self.fixup, text)

x = "%id% spam %id% egg %id%"

r = Replacer()

print r.replace(x)
print r.getcounter()

# if you really have to count the %id%s before you replace
# them, use len(r.pattern.findall(x)))

Hope this helps!

Cheers /F





More information about the Python-list mailing list