Count and replacing strings a texfile

Greg Jorgensen gregj at pobox.com
Tue Jan 23 23:30:40 EST 2001


Try this:

----
# read all text from the file
f = open(filename, "r")
s = f.read()
f.close()

# split text into a list at every occurence of %id%
t = s.split("%id%")
n = len(t)      # number of list elements
result = s[0]   # start with first element in list
# iterate over list, appending counter and next text chunk
for i in range(1,n):
        result += str(i) + s[i]

print "%s occurences replaced" % (n-1)
print result
----

--
Greg Jorgensen
Portland, Oregon, USA
gregj at pobox.com


In article <94i9ft$apq$1 at nnrp1.deja.com>,
  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.
>
> 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.
>
> I've been told that this is a perfect job for Perl, but I don't
> understand Perl.
> I merely understand Python. Well, I think I got the basics anyway. :)
>
> Anyone care to help me out for a minute to suggest what to do?
> Any pointers to examples are alot appreciated.
>
> Thanks.
>
> /Andreas
>
> Sent via Deja.com
> http://www.deja.com/
>


Sent via Deja.com
http://www.deja.com/



More information about the Python-list mailing list