Is there a cleaner way to replace characters in a text file?

Question:

i am trying to replace characters in a text file, the code works but it just seems too long. I was wondering if there is a different way to do this?

(It is a good way for me to learn a better way than just a long repetivite way)

Thanks

with open('documento.txt', 'r') as file:
    filedata = file.read()

filedata = filedata.replace('+', 'e')
filedata = filedata.replace('P', 'a')
filedata = filedata.replace('B', 'o')
filedata = filedata.replace('N', 's')
filedata = filedata.replace('K', 'n')
filedata = filedata.replace('X', 'r')
filedata = filedata.replace('Q', 'i')
filedata = filedata.replace('T', 'l')
filedata = filedata.replace('*', 'd')
filedata = filedata.replace('Y', 'u')
filedata = filedata.replace('_', 'c')
filedata = filedata.replace('V', 't')
filedata = filedata.replace('H', 'm')
filedata = filedata.replace('D', 'q')
filedata = filedata.replace('M', 'h')
filedata = filedata.replace('R', 'j')

with open('documento.txt', 'w') as file:
    file.write(filedata)
Asked By: Andrew

||

Answers:

In order to make this process more efficient, you may want to consider using a for loop with parallel lists containing what you want to replace and what you want to replace with. In your case, the code would look something like this:

beforeList = ['+', 'P', 'B', 'N', 'K', 'X', 'Q', 'T', '*', 'Y', '_', 'V', 'H', 'D', 'M', 'R']
afterList = ['e', 'a', 'o', 's', 'n', 'r', 'i', 'l', 'd', 'u', 'c', 't', 'm', 'q', 'h', 'j']

with open('documento.txt', 'r') as file:
    filedata = file.read()

for i in range(len(beforeList)):
    filedata = filedata.replace(beforeList[i], afterList[i])

with open('documento.txt', 'w') as file:
    file.write(filedata)

Because the characters you want to replace are ‘parallel’ to the characters you want to replace with, their indexes will match, allowing the for loop to go through each original character and replace them accordingly.

Answered By: skipperone
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.