繁体   English   中英

从mathml生成可由python计算的方程

[英]make equation from mathml which is computable by python

我的项目的一部分涉及从mathml获取方程式,该方程式可以发送给python.python应该容易处理方程式.mathml在下面给出。预期的python方程式也在下面给出。应该对该JavaScript进行哪些修改才能获得那..

    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);
    }

等式 在此处输入图片说明

mml =“ sin2x + cos2x + sin4x + 3”; u = stringifyMathML(mml); 警报(u)

输出是

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

但输出应该是

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

提供的mathml是::-

"<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>"

在jsfiddle中可以看到以下程序: http : //jsfiddle.net/user1989/g0ca42m2/2/应该对javascript进行什么更改才能获得预期的输出

您的“问题”来自您的“盲目”解析。

您的第一个输出是正确的。 msup sin 2防御x可以得到sin²(x)-> power(sin,2)(x)。

为了渲染功率(sin(x),2),您必须在进行翻译之前为下一个节点获取(作为“先行”)。 一个快速的解决方法应该是添加一个“ nextNode”参数(可以为null),并基于该参数进行解析。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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