Count and replacing strings a texfile
Carel Fellinger
cfelling at iae.nl
Mon Jan 22 19:05:22 EST 2001
puckoh at my-deja.com wrote:
> Hello.
> 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.
Do I understand you correctly, are all to be replaced strings equal?
> First, I need to count them all.
no need to count them then
> 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.
Well that just seems to easy, lets complicate it.
$ cat request.py
#!/usr/bin/python
##untested code made while I should be sleeping
import re
class Subs:
def __init__(self):
self.id = {}
def __call__(self, matched):
s = matched.group()[1:-1]
self.id[s] = self.id.get(s, 0) + 1
return "(%s=%d)" % (s, self.id[s])
r = re.compile('%.*?%')
data = open("spam").read()
data = r.sub(Subs(), data)
open("numbered-spam", "w").write(data)
$ cat spam
%spam%, %spam%, %spam% and %eggs%
%spam%, %spam%, %spam%, %bacon% and %eggs%
$ cat numbered-spam
(spam=1), (spam=2), (spam=3) and (eggs=1)
(spam=4), (spam=5), (spam=6), (bacon=1) and (eggs=2)
--
groetjes, carel
More information about the Python-list
mailing list