我是 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()
我该如何让脚本查找并替换正则表达式?
具体来说,我希望它找到在文本文件顶部指定的一些信息(元数据)。例如:
Title: This is the title
Author: This is the author
Date: This is the date
并将其转换为 LaTeX 格式。例如:
\title{This is the title}
\author{This is the author}
\date{This is the date}
也许我处理这个问题的方式不对。如果有比正则表达式更好的方法,请告诉我!
谢谢!
更新:感谢您在回答中发布一些示例代码!只要替换 findreplace 操作,我就可以让它工作,但我无法同时工作。现在的问题是我无法将它正确地集成到我已有的代码中。我将如何让脚本对以下代码段中的“outtext”执行多项操作?
for couple in findreplace:
outtext=s.replace(couple[0],couple[1])
s=outtext
最佳答案
>>> 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}
关于python - Python 查找和替换脚本中的正则表达式?更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3036706/