简体   繁体   中英

Issue while converting text/string into sympy math expression using sympify or parse_expr

I want my Python program to take text/string containing math formula/expression as input and convert it into latex format so that it can print/display in math format (eventually in a Word document). I am using the below code:


from sympy import *
text1 = '1/101'
#expr1 = parse_expr(text1, evaluate=False)
expr1 = sympify(text1, evaluate=False)
print('type of expr1 ', type(expr1), expr1)
latex_expr = latex(expr1)
print('type of latex expr ', type(latex_expr), '[', latex_expr, ']')

I have tried both parse_expr() as well as sympify().

For some unknown reason, the output of this program is as follows:

type of expr1 <class 'sympy.core.mul.Mul'> 1/101 type of latex expr <class 'str'> [ 1 \frac{1}{101} ]

I am not able to figure out why an extra 1 is appearing in the latex output before \frac. As per my observation, this is happening only when numerator of the fraction in text1 is 1. For all other numerators given in text1, the latex output is correct. I am using "evaluate=False" because I don't want the simplified form of the expression in the end output. For example, an input '2/4' needs to be displayed as 2/4 and not as 1/2.

Any help on this issue is most welcome.

You can post-process the resulting expression, for example:

def simplify_one(expr):
    if expr.is_Mul and (S.One in expr.args):
        return Mul(*[t for t in expr.args if t is not S.One])
    return expr

simplify_one(expr1)
# out: 1/101

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM