Help with mass remove in text file

R

rorley

I'm trying to open a text file, remove all instances of the words
"f=x;" and "i=x;" where x can be any number 0-14. Also, I want to
remove all { " or ) or ( or ' } each time one of those characters
occurs respectively. This is what I've been able to piece together...


import os, string
x = ("f=;")
y = ("i=;)
inputFile = open('abcd.txt','r')
data = inputFile.read()
inputFile.close()
search = string.find(data, x)
if search >=1:
data = data.replace(x)
data = data.replace(y)
outputFile = open('abcd.txt','w')
outputFile.write(data)
outputFile.close()


This doesn't work, even to just remove "f=;". Any help would be great.

Thanks,
Reece
 
S

Steve M

First, in your intro you say you want to remove all strings of the form
"f=n;" where n can be 0-14. So you want to remove "f=0;" and "f=1;" and
.... Later, you appear to be trying to remove "f=;" which may be what
you want but it doesn't match your described intentions.

Second, the formatting (whitespace) is all messed up on your post (at
least in googroups), so its not entirely clear what the program is
supposed to do.

Anyway, why do you say the program doesn't work? Does it generate an
error when you try to run it? Or is it doing what you say and not what
you mean?

I'm guessing that it will give (provided it doesn't end on a
SyntaxError) at least the following error:
TypeError: replace() takes at least 2 arguments (1 given)

This is because the line:
data = data.replace(x)

doesn't use enough arguments for the replace() method. You need to say
what to replace it with. Since you want to remove whatever string it
is, you can use the empty string as the replacement value:

data = data.replace(x, '') #That's two single quotes

Also, unless you want to make a regular expression, you might have to
do a replace() call on data 15 times, sort of like this:


for i in range(15):
text_to_remove = "f=%s;" % i
data = data.replace(text_to_remove, '')
 
P

Peter Hansen

I'm trying to open a text file, remove all instances of the words
"f=x;" and "i=x;" where x can be any number 0-14. Also, I want to
remove all { " or ) or ( or ' } each time one of those characters
occurs respectively. This is what I've been able to piece together...

See the thread titled "String Manipulation" which your classmate "jen"
started, which has several useful answers already.

Hopefully others will note that this is homework as well and not totally
hand you the answer on a platter, so you'll actually learn something.
Kudos to you for actually attempting it and posting your code though. ;-)

-Peter
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,261
Messages
2,571,308
Members
47,976
Latest member
AlanaKeech

Latest Threads

Top