简体   繁体   中英

make equation from mathml which is computable by python

Part of my projects deals with getting equation from mathml which can be send to python.The python should easily handle the equation .The mathml is given below .The expected python equation is also given below.What modification should be given to this javascript to get that..

    var mList = ['pow', 'sin', 'cos', 'tan', 'sqrt', 'π'];

    function getDOM(xmlstring) {
        parser=new DOMParser();
        return parser.parseFromString(xmlstring, "text/xml");
    }
    function remove_tags(node) {
        var result = "";
        var nodes = node.childNodes;
        var tagName = node.tagName;
        if (!nodes.length) {
            /*if(mList.indexOf(node.nodeValue) != -1 ) {
                result += 'math.'
            }*/
            if (node.nodeValue == "π") result += "pi";
            else if (node.nodeValue == " ") result += "";
            else result += node.nodeValue;
        } else if (tagName == "mfrac") {
            result += "("+remove_tags(nodes[0])+")/("+remove_tags(nodes[1])+")";
        } else if (tagName == "msup") {
            result += "power(("+remove_tags(nodes[0])+"),("+remove_tags(nodes[1])+"))";

        } else for (var i = 0; i < nodes.length; ++i) {
            result += remove_tags(nodes[i]);
        }
        if (tagName == "mfenced") result = "("+result+")";
        if (tagName == "msqrt") result = "sqrt("+result+")";

        return result;
    }
    function stringifyMathML(mml) {
       xmlDoc = getDOM(mml);  
       return remove_tags(xmlDoc.documentElement);
    }

the equation 在此处输入图片说明

mml="sin2x+cos2x+sin4x+3"; u=stringifyMathML(mml); alert(u)

the output is

 power((sin),(2))(x)+power((cos),(2))(x)+sin(4x+3)

but the ouput should be

  power(sin(x),2)+power(cos(x),2)+sin(4*x+3)

the mathml provided is ::-

"<math><msup><mi>sin</mi><mn>2</mn></msup><mfenced><mi>x</mi></mfenced><mo>+</mo><msup><mi>cos</mi><mn>2</mn></msup><mfenced><mi>x</mi></mfenced><mo>+</mo><mi>sin</mi><mfenced><mrow><mn>4</mn><mi>x</mi><mo>+</mo><mn>3</mn></mrow></mfenced></math>"

the following program can be seen in jsfiddle: http://jsfiddle.net/user1989/g0ca42m2/2/ What change should be made in the javascript to get the expected output

Your "problem" come from your "blind" parsing.

Your first output is right. msup sin 2 mfenced x gives you sin²(x) -> power(sin,2)(x).

In order to rendering power(sin(x),2) you have to fetch for the next node (as a "lookahead") before making your translation. A quick fix should be to add a "nextNode" argument (which may be null) and also base your parsing on it.

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