[英]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.