Python中使用正则表达式将LaTex分数转换为mathML

2024-09-27 00:17:38 发布

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

我有一些短信:

\frac{A}{B}

我需要将文本转换为:

^{pr2}$

我必须使用Python和regex。A和{}可以是更多的分数,因此函数必须是递归的,例如文本:

\frac{1+x}{1+\frac{1}{x}}

必须换成

<mfrac>
 <mrow>
  1+x
 </mrow>
 <mrow>
  1+
  <mfrac>
   <mrow>
    1
   </mrow>
   <mrow>
    x
   </mrow>
   </mfrac>
 </mrow>
</mfrac>

请帮助使用regex:)


Tags: 函数文本短信分数regexfracpr2mrow
1条回答
网友
1楼 · 发布于 2024-09-27 00:17:38

如果需要匹配默认python re module中的递归模式, 你可以像我一样处理我最近为之构建的递归注释 css预处理器。在

通常使用re只用于将文本拆分为标记,然后使用循环 使用嵌套级别变量查找所有语法。这是我的代码:

COMMENTsRe = re.compile( r"""
                        //   |
                        \n   |
                        /\*  |
                        \*/  
                        """, re.X ) 

def rm_comments( cut ):
  nocomment = 0 # no inside comment
  c = 1 # c-like comments, but nested
  cpp = 2 # c++like comments

  mode = nocomment
  clevel = 0 # nesting level of c-like comments
  matchesidx = []

  # in pure RE we cannot find nestesd structuries
  # so we are just finding all boundires and parse it here
  matches = COMMENTsRe.finditer( str(cut) )
  start = 0
  for i in matches:
    m = i.group()
    if mode == cpp:
      if m == "\n":
        matchesidx.append( ( start, i.end()-1 ) ) # -1 because without \n
        mode = nocomment
    elif mode == c:
      if m == "/*":
        clevel += 1
      if m == "*/":
        clevel -= 1
      if clevel == 0:
        matchesidx.append( ( start, i.end() ) )
        mode = nocomment
    else:
      if m == "//":
        start = i.start()
        mode = cpp
      elif m == "/*":
        start = i.start()
        mode = c
        clevel += 1

  cut.rm_and_save( matchesidx )

相关问题 更多 >

    热门问题