2013-05-29 23 views
2

我試圖從文件中提取乳膠代碼,但我不想要註釋; (評論以%開頭)。評論一直到行尾,但我不想刪除字面%(前\,如\%)。我會怎麼做呢?理想的情況下給出這樣的:刪除文本文件中的某一行後面的部分,除非在前面加上在python中

Lamport and has become the dominant method for using \TeX; few 
    people write in plain \TeX{} anymore. The current version is 
    \LaTeXe. % this is a comment 

    % This is a comment; it will not be shown in the final output. 
    % The following shows a little of the typesetting power of LaTeX: 
    \begin{align} 
    E &= mc^2        \\ 
    m &= \frac{m_0}{\sqrt{1-\frac{v^2}{c^2}}} 
    \end{align} 
    this is a \% literal symbol. 

我會得到:

Lamport and has become the dominant method for using \TeX; few 
    people write in plain \TeX{} anymore. The current version is 
    \LaTeXe. 


    \begin{align} 
    E &= mc^2        \\ 
    m &= \frac{m_0}{\sqrt{1-\frac{v^2}{c^2}}} 
    \end{align} 
    this is a \% literal symbol. 

有沒有辦法做到這一點與Python?

工作解決方案後編輯,謝謝大家。

r'(.*)(?<!\\\)%.*' 

回答

4

您可以做一個正則表達式替換(?<!\\)%.*,但這是脆弱的,例如, \verb!%!可能不是評論。

+0

有趣的,有多少其他角落情況下比 '動詞' 等有哪些?試圖追捕他們並且掩蓋他們是否是一個好主意? – mike

+0

可能不是。例如。 'listing'軟件包也有這樣一個命令,其他的也可以被定義。解析LaTeX的唯一好方法就是運行它。這是圖靈完整文檔描述語言的缺點。 – Joey

2

你可以從answer獲得靈感tex.stackechange.com。我們的想法是:

  1. 與其他非衝突的符號代替%\begin{verbatim}\end{verbatim}\verb|...|
  2. 之間使用(?<!\\)%.*正則表達式刪除評論
  3. 改回以前的保護%符號。

注意,在乳膠,以下

abc%comment 
def 

應該被解釋爲

abcdef 
+0

我不明白第1步,發生了什麼事? – mike

+0

這是爲了保護'%'字符不是開始註釋,因爲'\ verb ||'中的'%'或'{verbatim}'中的'%'字符不是特殊的。鏈接的答案讓Lisp中的代碼能夠做你想做的事情,它應該比我的僞代碼描述更容易理解。 –

相關問題