Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing characters in a file

Tags:

python

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()
like image 816
nrj Avatar asked May 12 '12 10:05

nrj


2 Answers

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"))
like image 111
robert Avatar answered Sep 29 '22 03:09

robert


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
like image 20
Siddy Hacks Avatar answered Sep 29 '22 04:09

Siddy Hacks