[Tutor] Multiple regex replacements, lists and for.

Will Geary artists00nly at gmail.com
Tue Oct 12 00:39:11 CEST 2010

Hello all,

I'm new to python and inexperienced in programming but I'm trying hard.
I have a shell script that I'm converting over to python.
Part of the script replaces some lines of text.
I can do this in python, and get the output I want, but so far only using sed.
Here's an example script:

import subprocess, re
list = ['Apples	the color red', 'Sky	i am the blue color', 'Grass	the
colour green is here', 'Sky	i am the blue color']

def oldway():
	sed_replacements = """
	sed = subprocess.Popen(['sed', sed_replacements],
stdin=subprocess.PIPE, stdout=subprocess.PIPE)
	data = sed.communicate("\n".join(list))[:-1]
	for x in data:
		print x

""" This produces:

>>>Grass	the colour green is here

Which is what I want"""

print "---------------"

def withoutsed():
	replacements = [
(r'.*red', 'RED'),
(r'.*blue.*', 'BLUE')]
	for z in list:
		for x,y in replacements:
			if re.match(x, z):
				print re.sub(x,y,z)
				print z

""" Produces:

>>>Sky	i am the blue color
>>>Grass	the colour green is here
>>>Grass	the colour green is here
>>>Sky	i am the blue color

Duplicate printing + other mess = I went wrong"""

I understand that it's doing what I tell it to, and that my for and if
statements are wrong.
What I want to do is replace matching lines and print them, and also
print the non-matching lines.
Can somebody please point me in the right direction?

Any other python pointers or help much appreciated,


More information about the Tutor mailing list