Converting a string into equation and resolve it

1.6k views Asked by At

All i need to do is convert a String into an simple object like: "1/4*x+ 1" to 1/4*x+ 1 I am extracting text from image and calculating the expression in the image. If i get: valid_text = 1/4*x+ 1= 1/6*x+ 1/2 from image, I am doing:

if 'x' in valid_text and '=' in valid_text:
    lhs = valid_text.rsplit('=', 1)[0]
    lhs = eval(lhs)
    rhs = valid_text.rsplit('=', 1)[1]
    rhs = eval(rhs)
    solution = solve(Eq(lhs, rhs), x)

I am using eval() function to return an object when i pass a String into it. But eval() function sometimes gives

rhs = eval(rhs)
File "<string>", line 1, in <module>
TypeError: 'int' object is not callable` **AND other inappropriate outputs.**

Is there any other way to get an object from String?

4

There are 4 answers

0
Ayush Jain On

This worked for me:

from sympy import *
from pydoc import locate
x, y, z, p, q, r, m, n, i, j = symbols('x y z p q r m n i j')
    if 'x' in valid_text and '=' in valid_text:
        t = locate('sympy.sympify')
        lhs = valid_text.rsplit('=', 1)[0]
        lhs = t(lhs)
        rhs = valid_text.rsplit('=', 1)[1]
        rhs = t(rhs)

        solution = solve(Eq(lhs, rhs), x)
3
farhawa On

Here is a complete solution

from sympy import solve
from sympy.abc import x, y, z, a, b
from sympy.parsing.sympy_parser import parse_expr

def solve_meThis(string_):
    try:
        lhs =  parse_expr(string_.split("=")[0])
        rhs =  parse_expr(string_.split("=")[1])
        solution = solve(lhs-rhs)
        return solution
    except:
        print "invalid equation"

valid_text = "1/4*x+ 1 = 1/6*x+ 1/2"
solve_meThis(valid_text)

>> -6
0
aTben0 On

It seems like you want to do symbolic calculus. python is not handling, as far as I know, this type of problem but the library simpy seems to do so. you can find information about it at http://scipy-lectures.github.io/advanced/sympy.html

Another approach would be to develop a grammar and syntaxic parser yourself but as already said, it's a long way to go.

Good luck!

0
user2357112 On

If the strings you're trying to parse represent SymPy expressions, then sympy.parsing.sympy_parser.parse_expr looks like the tool for the job.

In [8]: from sympy.parsing.sympy_parser import parse_expr

In [9]: parse_expr('2*x*sin(x)')
Out[9]: 2*x*sin(x)