Count and replacing strings a texfile

Moshe Zadka moshez at zadka.site.co.il
Tue Jan 23 08:14:35 EST 2001


On Mon, 22 Jan 2001 21:42:21 GMT, puckoh at my-deja.com 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.

counter = 0
def replace(_):
	global counter
	counter += 1
	return counter

id_re = re.compile('%id%')

s = open(file).read()
s = id_re.replace(s, replace)
open(file 'w').write(s)

You'll want to read the re module reference, in the standard library
reference.

it's-a-perfect-job-for-python-too-ly y'rs, Z.

-- 
Moshe Zadka <sig at zadka.site.co.il>
This is a signature anti-virus. 
Please stop the spread of signature viruses!
Fingerprint: 4BD1 7705 EEC0 260A 7F21  4817 C7FC A636 46D0 1BD6




More information about the Python-list mailing list