2014-10-30 34 views
0

我有下面這段代碼的LaTeX,並希望刪除\新出現的所有{「文本跨越多行」}。需要保留「跨越多行的文本」,只有「\ NEW {」和文件「}」中的某個位置需要被刪除,新的括號內應該保持不變。標籤和空格以及換行符需要保留。我已經嘗試編寫一個Python應用程序,但無法提供體面的輸出。最難的部分是你去掉括號的地方(可以在下一行)。刪除LaTeX的宏觀跨越多行

輸入:

\chapter{A \NEW{very} small \NEW{chapter}} 

\begin{itemize} 
    \item \NEW{Bla} 
    \item Dusse 
    \item Mekker 
\end{itemize} 

\NEW{This is new 
    multiline \texttt{text} with some things \TBD{TBD} in between 
    } The end 

輸出(預計):

\chapter{A very small chapter} 

\begin{itemize} 
    \item Bla 
    \item Dusse 
    \item Mekker 
\end{itemize} 

This is new 
    multiline \texttt{text} with some things \TBD{TBD} in between 
    The end 

在Python自己的解決方案,它的工作原理:

  • 讀線
    • 更換\ NEW {occurence帶有標記(0xff的炭)在管線
    • READ C
      • 檢查c是標記,標記組=真,設置嵌套括號marked_cnt,讀下一個字符
      • 否則檢查:C == '{',增量marked_cnt
      • 否則檢查:C == '}',標誌着==真,減量marked_cnt
      • 如果marked_cnt == -1,復位標記=假marked_cnt = 0,讀下一個字符
      • 打印 「有效」 字符
 
    #!/usr/bin/env python2.7 
    import sys 

    marker=chr(255) 
    marked=False 
    marked_cnt=0 

    fin = open("file.tex", "r") 
    fout = open("file.tex.out", "w") 

    for line in fin: 
     l = line.replace("\NEW{", marker) 
     for c in l: 
      if c == marker: 
       marked = True 
       marked_cnt = 0 
       continue 
      elif c == '{': 
       marked_cnt += 1 
      elif ((c == '}') and 
       (marked == True)): 
       marked_cnt -= 1 

      if marked_cnt == -1: 
       marked = False 
       marked_cnt = 0 
       continue 

      fout.write(c) 

    fin.close() 
    fout.close() 
+0

是否需要腳本應該在Python中?如果是這樣,你可能想分享你迄今爲止所做的,所以你可以看看它並修復它! – 2014-10-30 16:46:16

+1

如果唯一的興趣是輸出無效,那麼你可以將它設置爲no-op:'\ AtBeginDocument {\ renewcommand {\ NEW} { }}'。 – Werner 2014-10-30 17:15:25

回答

0

嘗試使用正則表達式:

import re 
myRe = re.compile(r'\\NEW{\w+}') 
for match in myRe.findall(myString): 
    newstring = match.replace('\NEW{','') 
    newstring = newstring.replace('}','') 
    myString.replace(match,newstring) 

然而,這並不能消除多行的問題。爲了解決這個問題,直接通過字符串,檢查然後打開和關閉括號:

while s.find('\\NEW{')>-1: 
    position = s.find('\\NEW{') 
    print(position, s[position:position+4]) 
    s = s[0:position]+s[position+5:] 
    trailexist = True 
    openbrackets = 0 

    while trailexist and position<len(s): 
     position +=1 
     print(len(s), position,s[position]) 
     if s[position] == '}' and openbrackets == 0: 
      s = s[:position]+s[position+1:] 
      trailexist = False 
      print("Removed!", position) 
     elif s[position] == '{': 
      openbrackets += 1 
      print('Openbrackets:',openbrackets) 
     elif s[position] == '}' and openbrackets>0: 
      openbrackets -= 1