Replacing characters in a file

I want to replace characters using encoding commands 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 tried the following code, but it only changes one character per line at a 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()
+5
source share
4 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')

It seems your code is trying to replace 'a' with 'e', ​​not 'e' with 'a'. To do this, you need the following:

import string
newcontents = contents.translate(string.maketrans("aes", "ea3"))
+9
source
>>> strs="this is a message"
>>> strs="".join(['a' if x=='e' else 'e' if x=='a' else '3' if x=='s' else x for x in strs])
>>> print(strs)
thi3 i3 e ma33ega

or, as Robert suggested , use a dictionary

>>> strs="this is a message"
>>> dic={'a':'e','e':'a','s':'3'}
>>> strs="".join((dic.get(x,x) for x in strs))
>>> print(strs)
thi3 i3 e ma33ega

or

>>> strs="this is a message"
>>> dic={'a':'e','e':'a','s':'3'}
>>> new_strs=''
>>> for x in strs:
     if x in dic:
        new_strs += dic[x]
     else:
        new_strs += x
>>> print(new_strs)

thi3 i3 e ma33ega
+3
source

It works great here.

>>> import codecs
>>> contents = codecs.open('foo.txt', encoding='utf-8').read()
>>> print contents
This is a message.

>>> print contents.replace('s', '3')
Thi3 i3 a me33age.

Note. If you want the second replacement to work, you should do this on newcontents:

newcontents = contents.replace('a','e')
newcontents = newcontents.replace('s', '3')
+1
source

You can also use regex

newcontents = re.sub(r"a","e",contents)
newcontents = re.sub(r"s","3",newcontents)
0
source

All Articles