optimization - Please help me optimize my Python code -


The Beginning Here! Perhaps an incredibly simple problem, forgive me in advance for raising up.

I am trying to put together a Python script which runs many search-and-replace functions and does something similar on a fixed field -text file. It works, but from a programming perspective, I doubt that it works well. How would I go about optimizing the tasks done on the 'outtext' variable? At the moment it is basically four times more ...

  Import the importation import then import structure import system 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 a lot for the couple at the place of search: Outtext = s.replace (couple [0], pair [1]) s = Find out for the outtext : Outtext = re.compile ('title: (. *)', Again. (R '\\ title' + r '{\ 1}', s) for s = outrext in findreplace: outtext = re.compile ('Author: (. *)', Re.I) .sub (r ' \\ Author '+ R' {\ 1} ', s) has been added to find s = outtext: outtext = re.compile (' Date: (. *) ', Rev.) .sub (r) S = Outtext # and Mississi section Outf = open (outFile, 'wb') outF.write (outtext.encode ('utf-8')) OutF Close ()  

For the last three replacements, it seems unnecessary for loops, because Loop Body Loop Variable Usage Does not. As a result, assigning a temporary external text variable is not necessary, it can be assigned directly to s .

This change code is too short:

 : s = s.replace (pair [0], pair [1]) s = re for adding to find .compile ('title: (. *)', Then I) .sub (r '\\ title {\ 1}', s) s = re.compile ('Author: (. *)', Rev. I) .sub (r '\\ author {\ 1}', S) s = re.compile ('Date: (. *.', Re.I) .sub (r '\\ date {\ 1}', s )  

Comments

Popular posts from this blog

windows - Heroku throws SQLITE3 Read only exception -

lex - Building a lexical Analyzer in Java -

python - rename keys in a dictionary -