Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing digits from a file

Tags:

python

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?

like image 814
nish Avatar asked Mar 10 '26 00:03

nish


2 Answers

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,
like image 133
Matthew Graves Avatar answered Mar 11 '26 13:03

Matthew Graves


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()]))
like image 42
noisy Avatar answered Mar 11 '26 13:03

noisy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!