# Python - First Attempt to Accelerate Latex Formula Editing

This post presents a python helper script that helps to accelerate Latex editing. The general idea is to

• implement a feature that can save a string expression to a variable
• implement an easy way to expand a string that conatins variables.

Note that Python already supports string template. For example:

1
2
3
4
A = "x + y - z"
B = "2x + 10y + z"
expression = "({A}) * ({B})".format(A = A, B = B)
print(expression)


This code above gives the following result:

(x + y - z) * (2x + 10y + z)


There are two issues with this approch:

• There are boilerplate code.
• It does not work well with latex command.

For example, we need to add extra {} for latex command:

1
2
3
4
A = "x + y - z"
B = "2x + 10y + z"
expression = r"\frac{{ {A} }} {{ {B} }}".format(A = A, B = B)
print(expression)


The code above gives us:

\frac{ x + y - z } { 2x + 10y + z }


The objective is to something like the following

Here, we use back apostrophe to expand a variable inside a string. In order to achive this, we need the following code

We could define normal python function to change the syntax a little bit:

1
2
3
4
5
6
7
8
9
10
def sum(expression, bottom=None, top=None, data=None):
_expression = expr(expression, data)
if bottom is None and top is None:
return "\sum{}".format(_expression)

if bottom is None:
return "\sum^{} {}".format(top, _expression)

if top is None:
return "\sum_{} {}".format(bottom, _expression)


Now we can do following:

This gives us:

\sum_{ t \in V } { \mathcal{M}_{q}(t) \cdot log \frac{\mathcal{M}_{q}(t)}{\mathcal{M}_{d}(t)} } = \sum_{ t \in V } { \mathcal{M}_{q}(t) \cdot log \mathcal{M}_{q}(t) } - \sum_{ t \in V } { \mathcal{M}_{q}(t) \cdot log \mathcal{M}_{d}(t) }


We can also define customized function. However, this time we need to specify the local data:

The code can be found at https://gist.github.com/meretciel/3b372d7c0c11189239ae7ceb00a74f32

----- END -----