Regular expressions in Python find-and-replace script? Refresh

I'm new to Python scripting, so please forgive me in advance if the answer to this question seems obvious.

I am trying to build a large-scale find-and-replace script using Python. I am using code similar to the following:

infile = sys.argv[1]
charenc = sys.argv[2]
outFile=infile+'.output'

findreplace = [
('term1', 'term2'),
]

inF = open(infile,'rb')
s=unicode(inF.read(),charenc)
inF.close()

for couple in findreplace:
    outtext=s.replace(couple[0],couple[1])
    s=outtext

outF = open(outFile,'wb')
outF.write(outtext.encode('utf-8'))
outF.close()

How can I make a script find and replace regular expressions?

In particular, I want him to find some information (metadata) listed at the top of the text file. For instance:

Title: This is the title
Author: This is the author
Date: This is the date

and convert it to LaTeX format. For instance:

\title{This is the title}
\author{This is the author}
\date{This is the date}

Perhaps I will solve it wrong. If there is a better way than regular expressions, please let me know!

Thank!

: ! , findreplace, . , , . , script "outtext" ?

for couple in findreplace:
    outtext=s.replace(couple[0],couple[1])
    s=outtext
+3
4
>>> import re
>>> s = """Title: This is the title
... Author: This is the author
... Date: This is the date"""
>>> p = re.compile(r'^(\w+):\s*(.+)$', re.M)
>>> print p.sub(r'\\\1{\2}', s)
\Title{This is the title}
\Author{This is the author}
\Date{This is the date}

, :

def repl_cb(m):
    return "\\%s{%s}" %(m.group(1).lower(), m.group(2))

p = re.compile(r'^(\w+):\s*(.+)$', re.M)
print p.sub(repl_cb, s)

\title{This is the title}
\author{This is the author}
\date{This is the date}

+5
+1

, , , :

^([^:]+): (.*)

\\\1{\2}
0
>>> import re
>>> m = 'title', 'author', 'date'
>>> s = """Title: This is the title
Author: This is the author
Date: This is the date"""
>>> for i in m:
    s = re.compile(i+': (.*)', re.I).sub(r'\\' + i + r'{\1}', s)


>>> print(s)
\title{This is the title}
\author{This is the author}
\date{This is the date}
0

Source: https://habr.com/ru/post/1749918/


All Articles