text manipulation
Juho Schultz
juho.schultz at helsinki.fi
Fri Dec 16 06:25:13 EST 2005
Johhny wrote:
> Hello,
>
> I am trying to write a script in python (to replace a perl script with
> limited functionality). Now I have some issues. Currently I am using
> the perl to load the file then regex parse certain lines to remove
> characters (uncomment lines and change variables). I would like to take
> that into the python script. I have had a look at the module "string"
> and I dont think its what Im looking for.
>
> Here is an example of some text I would like to manipulate
>
> #comment here
> #user_defined_variable = no
> #
>
> I would like to make that
>
> #comment here
> user_defined_variable = yes
> #
>
> With perl/sed Its very easy, However Im having issues to do it in
> python. Any advice would be great.
>
> Regards,
>
> Johhny.
>
Have you also looked at the built-in string methods?
The following script is probably something you
could start with - it just uncomments lines
and replaces values of some variables.
# dictionary of the variable names
# contains the replacement values
newvalues = {'userdefinedvar1':'yes',
'userdefinedvar2':'123.654.345.234'}
# read file to input
output = []
for line in input:
# check if it is a comment with "="
if line.startswith('#') and ('=' in line):
name, oldvalue = (line.lstrip('#')).split('=')
# line.lstrip removes leading comments,
# split('=') finds the assignment
if newvalues.has_key(name):
# replace line
output.append("%s = %s" % (name, newvalue[name]))
else:
# or just uncomment
output.append("%s = %s" % (name, oldvalue))
else:
output.append(line)
# write output to file
More information about the Python-list
mailing list