help with search & replace

Mike Meyer mwm at mired.org
Thu Dec 12 14:01:37 EST 2002


Bill Blue <billblue at cham.com> writes:
> I have a text file that has numbers is many places thru out the file
> ie "20:22:12" .  I need to be able to create a new file and make
> changes only to those numbers above.  I used this to find them
> 
> import re,string,sys
> 
> if = open("infile.txt","r")
> of = open("outfile.txt,"w")
> for line in if.xreadlines():
> 	fs = re.compile(r"\d+:\d+:\d+").findall(line)  # there may be
> more than one in a line.
> 	if fs:
> 		for num in fs:
> 			of.write(lne.replace(num,num[0:5]+"00")) # the
> replace text is not always the same
> 	else:
> 		of.write(line)  # for line where no match is found
> 
> The above works if there is only 1 match or number on a line, if there
> are more that one then I get multiple lines in the output file.   in
> most cases there may be 3-6 matches on one line.

Of course it outputs multiple lines. You *told* it to output multiple
lines. One for each match, in fact.

Try it this way (other fixes include not using a reserved word as a
variable and only compiling the regular expression once):

infile = open("infile.txt", "r")
outfile = open("outfile.txt", "r")
regexp = re.compile(r"\d+:\d+:\d+")
for line in infile.xreadlines():
   fs = regexp.findall(line)
   if fs:
      for num in fs:
         line = line.replace(num, num[0:5] + "00")
   outfile.write(line)

        <mike
-- 
Mike Meyer <mwm at mired.org>			http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.



More information about the Python-list mailing list