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

标签 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()

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

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

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/

相关文章:

python - python中的负战俘

javascript 正则表达式 维度

regex - 如何将名字拆分为姓氏和首字母

python - 在 Raspberry Pi 上连续运行 Pimoroni Buttonshim 的 Python 代码导致卡住

python - 创建数据透视表并获取 Pandas Dataframe 中的计数

python - Flask 重定向后的 Twilio MessagingResponse()

python - 强化学习如何通过高斯策略进行连续控制?

python - 为 6 个字符的代码编写正则表达式

Java:使用模式和匹配器解析空格

正则表达式匹配除 ACTION LOGDIR ="/vz/actionlog"之外的任何其他内容