Python查找和替换脚本中的正则表达式?更新

木川 *_* 炎星 3 python regex

我是Python脚本的新手,所以如果这个问题的答案看起来很明显,请提前原谅我.

我正在尝试使用Python组建一个大规模的查找和替换脚本.我使用的代码类似于以下内容:

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()
Run Code Online (Sandbox Code Playgroud)

如何让脚本执行查找并替换正则表达式?

具体来说,我希望它能够找到文本文件顶部指定的一些信息(元数据).例如:

Title: This is the title
Author: This is the author
Date: This is the date
Run Code Online (Sandbox Code Playgroud)

并将其转换为LaTeX格式.例如:

\title{This is the title}
\author{This is the author}
\date{This is the date}
Run Code Online (Sandbox Code Playgroud)

也许我正在以错误的方式解决这个问题.如果有比正则表达更好的方式,请告诉我!

谢谢!

更新:感谢您在答案中发布一些示例代码!只要我替换了findreplace动作,我就可以让它工作,但我不能让它们都工作.现在的问题是我无法将其正确地集成到我所拥有的代码中.如何让脚本在下面的代码段中对'outtext'执行多项操作?

for couple in findreplace:
    outtext=s.replace(couple[0],couple[1])
    s=outtext
Run Code Online (Sandbox Code Playgroud)

Ama*_*osh 5

>>> 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}
Run Code Online (Sandbox Code Playgroud)

要更改大小写,请使用函数作为替换参数:

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)
Run Code Online (Sandbox Code Playgroud)

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