I have a file of the form:
car1 auto1 automobile1 machine4 motorcar1
bridge1 span5
road1 route2
But I want to remove the integers so that my file looks like:
car auto automobile machine motorcar
bridge span
road route
I am trying to read the file character by character, and if a character is a digit, skip it. But I am printing them in a new file. How can I make changes in the input file itself?
Using regular expressions:
import re
import fileinput
for line in fileinput.input("your_file.txt", inplace=True):
print re.sub("\d+", "", line),
note: fileinput is a nice module for working with files.
Edit: for better performance/less flexibility you can use:
import fileinput
import string
for line in fileinput.input("your_file.txt", inplace=True):
print line.translate(None, string.digits),
For multiple edits/replaces:
import fileinput
import re
for line in fileinput.input("your_file.txt", inplace=True):
#remove digits
result = ''.join(i for i in line if not i.isdigit())
#remove dollar signs
result = result.replace("$","")
#some other regex, removes all y's
result = re.sub("[Yy]+", "", result)
print result,
with open('input.txt', 'r') as f1, open('output.txt', 'w') as f2:
f2.write("".join([c for c in f1.read() if not c.isdigit()]))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With