Beginner here! Forgive me in advance for raising what is probably an incredibly simple problem.
I've been trying to put together a Python script that runs multiple find-and-replace actions and a few similar things on a specified plain-text file. It works, but from a programming perspective I doubt it works well. How would I best go about optimizing the actions made upon the 'outtext' variable? At the moment it's basically doing a very similar thing four times over...
import binascii
import re
import struct
import sys
infile = sys.argv[1]
charenc = sys.argv[2]
outFile=infile+'.tex'
findreplace = [
('TERM1', 'TERM2'),
('TERM3', 'TERM4'),
('TERM5', 'TERM6'),
]
inF = open(infile,'rb')
s=unicode(inF.read(),charenc)
inF.close()
# THIS IS VERY MESSY.
for couple in findreplace:
outtext=s.replace(couple[0],couple[1])
s=outtext
for couple in findreplace:
outtext=re.compile('Title: (.*)', re.I).sub(r'\\title'+ r'{\1}', s)
s=outtext
for couple in findreplace:
outtext=re.compile('Author: (.*)', re.I).sub(r'\\author'+ r'{\1}', s)
s=outtext
for couple in findreplace:
outtext=re.compile('Date: (.*)', re.I).sub(r'\\date'+ r'{\1}', s)
s=outtext
# END MESSY SECTION.
outF = open(outFile,'wb')
outF.write(outtext.encode('utf-8'))
outF.close()