Python Markdown messed up math formula

2019-04-16 01:22发布

问题:

When converting the content from markdown to HTML format, the following math function

${\{y_{i}, x_{i1}, ..., x_{id}\}}_{i=1}^{n}$ 

got converted to

${{y_{i}, x_{i1}, ..., x_{id}}}<em>{i=1}^{n}$

Is there a way to tell Python's Markdown not doing this? Thanks!

回答1:

Yes, the math syntax conflicts with Markdown's syntax. You need to tell the parser to not treat that as Markdown.

You have a few different ways to do that:

  1. Wrap the Math function in raw HTML. Markdown is not processed inside raw block-level HTML. So wrap your math in a div:

    <div>${\{y_{i}, x_{i1}, ..., x_{id}\}}_{i=1}^{n}$</div>
    
  2. Use a third-party extension (also here) which offers a way to mark up a section of a document as Math. You need to install one of the extensions and then tell Python-Markdown to use it.For example, to install Python-Markdown-Math, do the following:

    pip install python-markdown-math
    

    Then, in your Python code, you can tell Markdown to use the extension:

    markdown.markdown(src, extensions=['mdx-math'])
    

    Note that in order to avoid conflicts with dollar signs used for for designating money (normal usage), most of the extensions do not support using single dollar sign as a wrapper. In that case, you will need to use double-dollar signs ($$...$$). Or you could turn on support for single dollar signs like this:

    markdown.markdown(
        src, 
        extensions=['mdx_math'], 
        extension_configs={
            'mdx_math': {'enable_dollar_delimiter': True}
        }
    )
    

    As an aside, the Arithmatex Extension offers support for single dollar signs by default. However, it is part of a larger package of extensions. If you only need the one, Python-Markdown-Math will serve you just fine (each is developed by a different member of the Python-Markdown team).