将正则表达式文档的结果写回python中的文档

时间:2013-01-04 07:20:42

标签: python regex latex

我正在尝试创建一个python脚本,在排版之前立即在LaTeX文档上执行一些正则表达式替换,但我似乎遇到了一些问题,使得替换生效。我的脚本如下:

# -*- coding: utf-8 -*-
import os, re, sys
tex = sys.argv[-1]
tex_file = open(tex, "r+")
tex_file_data = tex_file.read()

# DO SOME REGEXES
tex_file_data = re.sub(r"\b_(.*?)_\b", r"\emph{\1}", tex_file_data)
tex_file.write(tex_file_data)

# PROCESS THE DOCUMENT
os.system("xelatex --shell-escape " + tex_file.name)

但是,每次尝试使用此脚本处理文档时,都会收到通常的! Missing $ inserted.错误。根据正则表达式,这些下划线应该用合适的语法替换。但是,如果我将最后一行替换为print(tex_file_data),控制台将显示文档,其中的更改已生效。据我所知,问题似乎是编辑后的文件没有正确保存,但我不确定我做错了什么。

我如何解决此问题,以便脚本可用于处理文档?

编辑:在@Yuushi的建议下,我编写了如下脚本:

# -*- coding: utf-8 -*-
import os, re, sys
with open(sys.argv[-1], "r+") as tex_file:
  tex_file_data = tex_file.read()
  tex_file_data = re.sub(r"\_(.*)\_", r"\\emph{\1}", tex_file_data)
  tex_file.write(tex_file_data)
os.system("xelatex --shell-escape " + tex_file.name)

但是,我仍然收到! Missing $ inserted.错误,这表示原始文档仍然被发送到LaTeX编译器而不是正则数据库。

1 个答案:

答案 0 :(得分:1)

你可能有两个问题。首先,在read之后,流设置为结束位置,因此在您致电tex_file.seek(0)之前,您需要使用write将其重置为开头。其次,您永远不会关闭文件,并且写入可能是缓冲的,因此最后需要tex_file.close()。更好的是使用with语句:

with open(sys.argv[-1], 'r+') as tex_file:
    tex_file_data - tex_file.read()
    tex_file_data = re.sub(r"\_(.*)\_", r"\\emph{\1}", tex_file_data)
    tex_file.seek(0)
    tex_file.write(tex_file_data)

os.system("xelatex --shell-escape " + tex_file.name)