Categories
Uncategorized

Using re.sub( ) – Python

#!/usr/bin/python
# import the 're' module
import re

# file1 is where the original text is
file1="the/file1.txt"
# file2 is where the modified text will be written
file2="the/file2.txt"

# open both files, one for reading the other for writing
f1=open(file1,"r")
f2=open(file2,"w")

# patterns you want to search
# in this example it's everything except digits and new lines.
pattern="[^\d\n]"
# what you wan to replace it with (nothing)
replace=""

# start the loop
for line in f1:
	this=re.sub(pattern,replace,line)
	f2.write(this)

# close files now that we're done.
f1.close()
f2.close()

This is the original text

# [file1.txt]
this 1s ju2t some stuff with som3 num4er5

And this is what you get after deleting everything except digits.

# [file2.txt]
12345

More info on Python regular expressions.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s