Skip to content Skip to sidebar Skip to footer

Latex Command Substitution Using Regexp In Python

I wrote a very ugly script in order to parse some rows of latex in python and doing string substitution. I'm here because I'm want to write something to be proud of, and learn :P

Solution 1:

To answer your questions,

  • First problem: You can use (named) groups
  • Second problem: In Python3, you can use r"\btree" to deal with the backslash gracefully.

Using a latex parser like github.com/alvinwan/TexSoup, we can simplify the code a bit. I know OP has asked for regex, but if OP is tool-agnostic, a parser would be more robust.

Nice Function

We can abstract this into a replace function

def replaceTex(soup, command, replacement):
    for node in soup.find_all(command):
        node.replace(replacement.format(args=node.args))

Then, use this replaceTex function in the following way

>>>soup = TexSoup(r"\section{hello} text \bra{(.)} haha \ket{(.)}lol")>>>replaceTex('bra', r"|{args[0]}\rangle")>>>replaceTex('ket', r"\langle{args[0]}|")>>>soup
\section{hello} text \langle(.)| haha |(.)\ranglelol

Demo

Here's a self-contained demonstration, based on TexSoup:

>>>import TexSoup>>>soup = TexSoup(r"\section{hello} text \bra{(.)} haha \ket{(.)}lol")>>>soup
\section{hello} text \bra{(.)} haha \ket{(.)}lol
>>>soup.ket.replace(r"|{args[0]}\rangle".format(args=soup.ket.args))>>>soup.bra.replace(r"\langle{args[0]}|".format(args=soup.bra.args))>>>soup
\section{hello} text \langle(.)| haha |(.)\ranglelol

Post a Comment for "Latex Command Substitution Using Regexp In Python"