从latex行Python解析REGEX命令

2024-05-26 04:22:59 发布

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

我试图解析并删除从每一行加载的\command\textit,等等…)(从.tex文件或lilypond文件的其他命令中,[\clef, \key, \time])中。在

我怎么能那样做?在

我所做的一切

import re
f = open('example.tex')
lines = f.readlines()
f.close()

pattern = '^\\*([a-z]|[0-9])' # this is the wrong regex!!
clean = []
for line in lines:
    remove = re.match(pattern, line)
    if remove:
        clean.append(remove.group())

print(clean)

示例

输入

^{pr2}$

预期产量

More things
Anything

Tags: 文件key命令recleantimelinecommand
2条回答

这将起作用:

'\\\w+\s'

它搜索反斜杠,然后搜索一个或多个字符和一个空格。在

您可以使用this pattern^\\[^\s]*使用简单的regex替换:

python中的示例代码:

import re
p = re.compile(r"^\\[^\s]*", re.MULTILINE)

str = '''
\item More things
\subitem Anything
'''

subst = ""

print re.sub(p, subst, str)

结果是:

^{pr2}$

相关问题 更多 >