2013-01-04 26 views
1

我試圖創建一個python腳本,在排版前立即在LaTeX文檔上執行一些正則表達式替換,但我似乎遇到了一些問題使替代生效。我的腳本如下:將正則表達式文檔的結果寫回python中的文檔

# -*- 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的建議下,我editted腳本如下:

# -*- 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編譯器而不是正則表達式。

+0

您仍然缺少'seek'。我用一個完整的例子編輯了我的答案。 – Yuushi

回答

1

您可能有兩個問題。首先,在read之後,流被設置爲結束位置,因此在您致電write之前,您需要將其重置爲開頭的tex_file.seek(0)。其次,你永遠不會關閉文件,並且寫入可能被緩衝,因此最後需要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) 
相關問題