It will be something like that. For the moment, I'm just implemented the basics of presentation mathml. I will add features as I need them.
After running it, sympify should be called. What do you think about it?
def parseMML(mmlinput):
from lxml import etree
from StringIO import *
from lxml import objectify
mmlinput= mmlinput.replace(' xmlns="', ' xmlnamespace="')
parser = etree.XMLParser(ns_clean=True,remove_pis=True,remove_comments=True)
tree = etree.parse(StringIO(mmlinput), parser)
objectify.deannotate(tree,cleanup_namespaces=True,xsi=True,xsi_nil=True)
mmlinput=etree.tostring(tree.getroot())
exppy="" #this is the python expression
symvars=[] #these are symbolic variables which can eventually take part in the expression
events = ("start", "end")
level = 0
context = etree.iterparse(StringIO(mmlinput),events=events)
for action, elem in context:
if (action=='start') and (elem.tag=='mfrac'):
level += 1
mmlaux=etree.tostring(elem[0])
(a,b)=parseMML(mmlaux)
symvars.append(b)
exppy+=a
exppy+='/'
mmlaux=etree.tostring(elem[1])
(a,b)=parseMML(mmlaux)
symvars.append(b)
exppy+=a
if (action=='end') and (elem.tag=='mfrac'):
level -= 1
if level:
continue
if (action=='start') and (elem.tag=='mrow'):
exppy+='('
if (action=='end') and (elem.tag=='mrow'):
exppy+=')'
if action=='start' and elem.tag=='mn': #this is a number
exppy+=elem.text
if action=='start' and elem.tag=='mi': #this is a variable
exppy+=elem.text
symvars.append(elem.text) #we'll return the variable, so sympy can sympify it afterwards
if action=='start' and elem.tag=='mo': #this is a operation
exppy+=elem.text
return (exppy, symvars)
exppy='((3)/(57))'