How to convert LaTeX to mathml and put it to right place of the file?

In Python, how can I change the text in a file? Namely. I have a file with tags mathematical formulas of the form <latex>e=mc^2</latex> in the middle of text. I would like to convert them to mathml-formulas and save them back to the file on their proper place. For example, if the file contains the line:

Then Pythagoras proved that <latex>a^2+b^2=c^2</latex> for right angled triangles.

the line after the conversion should be

Then Pythagoras proved that <math xmlns="http://www.w3.org/1998/Math/MathML" display="inline"><mrow><msup><mi>a</mi><mn>2</mn></msup><mo>&#x0002B;</mo><msup><mi>b</mi><mn>2</mn></msup><mo>&#x0003D;</mo><msup><mi>c</mi><mn>2</mn></msup></mrow></math> for right angled triangles.

My code contain the import latex2mathm.converter.

Just to clarify, your text file contains things like this, verbatim?

less than latex greater than e=mc^2 less than /latex greater than

not this

<latex> e=mc^2 </latex>

?

The file contain the text as in the latter one example. I just tried to write the tags in my original post but it seems that the forum lost those.

Use the </> button in the UI or use code-fences like this:

```
Your code or text here.
```

Have you tried latex2mathml · PyPI?

Yes. Conversion works well. The problem is that how one can replace the <latex>...</latex>-parts in the file by the mathml-tags.

At a high level, read the file into memory, find the latex parts, replace with mathml parts, and write the file. Since your tags look like html (xml) tags, I believe that you might be able to use htmlparser to find the tagged parts, much as we did in idlelib.help to find a subset of html tags to render idle.html in a tkinter text widget.