【问题标题】:From plain text to TEX - Javascript [closed]从纯文本到 TEX - Javascript [关闭]
【发布时间】:2019-08-11 09:00:01
【问题描述】:

我正在构建一个数学应用程序,我想展示用 javascript (nodejs) 编写的数学公式。所以我会将纯文本转换为 TEX 格式。 从这样的公式:

(25*5)/6

这样的公式:

\frac{(25 \cdot 5)}{6}

为了好的设计:

如果有其他已知的方法,请告诉我。 非常感谢!

【问题讨论】:

  • 您应该找到一个解析器,并根据您的需要对其进行更新。
  • 你能告诉我任何解析器吗?
  • 也许是 PEG.js,pegjs.org
  • 这样我必须从零开始构建解析器(如果我理解 pegjs 的目的)。我正在搜索一些现有的库来将我的纯文本转换为 TEX。
  • 好,我来写一个简单的tex解析器。

标签: node.js math latex formula tex


【解决方案1】:

我已将 this 表达式解析器从 java 重写为 javascript。不是最直接的方法。请注意,这未经广泛测试。

function texFromExpression(str){
    var pos = -1, ch;
    function nextChar(){
        ch = (++pos < str.length) ? str.charAt(pos) : -1;
    }
    function eat(charToEat) {
        while (ch == ' ') nextChar();
        if (ch == charToEat) {
            nextChar();
            return true;
        }
        return false;
    }
    function parse(){
        nextChar();
        var x = parseExpression();
        if (pos < str.length) throw `Unexpected: ${ch}`
        return x;
    }
    function parseExpression() {
        var x = parseTerm();
        for (;;) {
            if      (eat('+')) x = `${x} + ${parseTerm()}` // addition
            else if (eat('-')) x = `${x} - ${parseTerm()}` // subtraction
            else return x;
        }
    }
    function parseTerm() {
        var x = parseFactor();
        for (;;) {
            if      (eat('*')) x=`${x} \\cdot ${parseTerm()}`; // multiplication
            else if (eat('/')) x= `\\frac{${x}}{${parseTerm()}}`; // division
            else return x;
        }
    }
    function parseFactor() {
        if (eat('+')) return `${parseFactor()}`; // unary plus
        if (eat('-')) return `-${parseFactor()}`; // unary minus

        var x;
        var startPos = pos;
        if (eat('(')) { // parentheses
            x = `{(${parseExpression()})}`
            eat(')');
        } else if ((ch >= '0' && ch <= '9') || ch == '.') { // numbers
            while ((ch >= '0' && ch <= '9') || ch == '.') nextChar();
            x = str.substring(startPos, pos);
        } else if (ch >= 'a' && ch <= 'z') { // variables
            while (ch >= 'a' && ch <= 'z') nextChar();
            x= str.substring(startPos, pos);
            if(x.length>1){
                x = `\\${x} {${parseFactor()}}`;
            }
        } else {
            throw `Unexpected: ${ch}`
        }
        if (eat('^')) x = `${x} ^ {${parseFactor()}}` //superscript
        if(eat('_')) x = `${x}_{${parseFactor()}}`;

        return x;
    }
    return `$${parse()}$`;
}

【讨论】:

  • 你是个天才。非常感谢您的帮助!
猜你喜欢
  • 1970-01-01
  • 2015-06-29
  • 2016-03-12
  • 1970-01-01
  • 2011-09-14
  • 1970-01-01
  • 1970-01-01
  • 2012-01-05
  • 2012-02-03
相关资源
最近更新 更多