I want to replace characters using encoding instructions in a text file.
My text file contains the line:
This is a message
I want to replace a -> e
,e -> a
,s -> 3
So the line reads:
Thi3 i3 e massega
I have tried the following code but it only changes one character in the line at one time.
import sys
import codecs
def encode():
path = "C:\Users\user\Desktop"
basename = "assgn2part1.txt"
filename = path + "\\" + basename
#file = open(filename, "rt")
f = codecs.open(filename,encoding='utf-8')
contents = f.read()
print contents ,"\n"
newcontents = contents.replace('a','e')
newcontents = contents.replace('s', '3')
print newcontents
f.close()
Replace this:
newcontents = contents.replace('a','e')
newcontents = contents.replace('s', '3')
with this:
newcontents = contents.replace('a','e')
newcontents = newcontents.replace('s', '3')
Or better yet:
newcontents = contents.replace('a','e').replace('s', '3')
Your code only appears to attempt replacing 'a' with 'e', not 'e' with 'a'. For that, you need the following:
import string
newcontents = contents.translate(string.maketrans("aes", "ea3"))
Here is a simple gist you can see and get some help
x = open("e:/a.txt" )
s=x.read().replace(''a", "xy" )
x.close()
//Now open the file in write mode and write the string with replaced
x=open("e:/a.txt","w")
x.write(s)
x.close
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