删除横跨多行的LaTeX宏

2024-03-29 02:39:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我有下面的一段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

输出(预期):

^{2}$

在python中使用自己的解决方案:

  • 阅读行
    • 用标记替换\NEW{occurrence(char 0xff)
    • 连续读c
      • 检查c是否为marker,设置marked=True,为嵌套方括号设置marked\u cnt,读取下一个字符
      • 否则检查:c=='{',增量标记为\u cnt
      • 否则检查:c='}'和标记==True,减量标记为\u cnt
      • 如果已标记的字符==-1,重置标记为False,标记的标记为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()

Tags: in标记文本falsetruenew地方item
1条回答
网友
1楼 · 发布于 2024-03-29 02:39:29

尝试使用正则表达式:

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)

然而,这并不能解决多行问题。要解决这个问题,请直接遍历字符串,然后检查括号的开合:

^{pr2}$

相关问题 更多 >