【问题标题】:Latex fractions to mathML in Python with regex使用正则表达式在 Python 中将乳胶分数转换为 mathML
【发布时间】:2014-01-20 23:54:14
【问题描述】:

我有一些文字:

\frac{A}{B}

我需要将此文本转换为表单:

<mfrac>
 <mrow>
  A
 </mrow>
 <mrow>
  B
 </mrow>
</mfrac>

我必须使用 Python 和正则表达式。 AB 可以是进一步的分数,所以函数必须是递归的,例如 text:

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

必须改成

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

请帮助使用正则表达式:)

【问题讨论】:

  • 您不能使用 re 模块在完整的正则表达式中执行此操作,因为 re 模块没有递归功能。但是,您可以安装并尝试实现此功能的替代正则表达式模块(名为:regex):更多信息:pypi.python.org/pypi/regex
  • @CasimiretHippolyte 具有递归功能的正则表达式是什么样的?
  • 大概您所需的输出只是使用元语法,而您并没有真正生成 &lt;mrow&gt; 1+x &lt;/mrow&gt; ? (MathML 应该是&lt;mrow&gt;&lt;mn&gt;1&lt;/mn&gt;&lt;mo&gt;+&lt;/mo&gt;&lt;mi&gt;x&lt;/mi&gt;&lt;/mrow&gt;

标签: python regex latex fractions mathml


【解决方案1】:

如果你需要匹配默认python re模块中的递归模式, 你可以像我一样为我最近构建的递归 cmets 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 )

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-01-06
    • 2014-03-24
    • 1970-01-01
    • 1970-01-01
    • 2014-11-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多