我有以下的LaTeX代码,并希望删除\ NEW {“跨越多行的文本”}的所有出现。需要保留“跨越多行的文本”,只需删除“\ NEW {”和文件“}”中的某个位置,新的括号内应保持不变。需要保留选项卡,空格和换行符。我已经尝试编写python应用程序,但无法生成合适的输出。最困难的部分是你删除括号的位置(可以在下一行)。
输入:
\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中的自有解决方案有效:
#!/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 :(得分: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