前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Python3 调用 Node.js 解

Python3 调用 Node.js 解

作者头像
py3study
发布2020-01-06 15:21:14
2.1K0
发布2020-01-06 15:21:14
举报
文章被收录于专栏:python3

【背景】

下面的文本(https://www.aimsciences.org/article/doi/10.3934/cpaa.2009.8.1725

代码语言:javascript
复制
Global well-posedness for the $L^2$-critical Hartree  equation on $\mathbb{R}^n$, $n\ge 3$

被 MathJax 渲染成

xxx.png
xxx.png

需要解析成

代码语言:javascript
复制
Global well-posedness for the L2-critical Hartree equation on Rn, n≥3

【环境】

  • OS 版本:Windows10 x64 1803
  • Python版本:Python 3.6.5 x64
  • Node.js 版本:Node.js 10.14.2
  • mathjax-node:mathjax-node@2.1.1
代码语言:javascript
复制
npm install -g mathjax-node
npm list --depth=0 -global
set node_path=C:\Users\walker\AppData\Roaming\npm\node_modules

【t.js】

代码语言:javascript
复制
var mjAPI = require("mathjax-node")
function MathJax2Xml(mathjaxFormula) {
  mjAPI.config({
  });
  mjAPI.start();
  mjAPI.typeset({
    math: mathjaxFormula,
    format: "TeX",
    mml: true
  }, function (data) {
    if (!data.errors) {
      console.log(data.mml);
    } else {
      console.log("<p>ERROR</p>");
    }
  });
}

var args = process.argv.splice(2);
MathJax2Xml(args[0])

【t.py】

代码语言:javascript
复制
#encoding: utf-8
#author: walker
# date: 2019-05-17
# summary: 调用 nodejs 处理 mathjax 公式

import re
from subprocess import check_output
from parsel import Selector

def GetXml(mathjaxFormula):
    r""" 将 mathjax 公式转为 xml """
    bytesTxt = check_output(['node', 't.js', mathjaxFormula], timeout=100)
    xmlText = bytesTxt.decode('utf8').strip()
    # print('xmlText: %s' % xmlText)
    return xmlText

def Xml2PlainText(xmlText):
    r""" 将 xml 转换为普通文本 """
    sel = Selector(text=xmlText, type='xml')
    plainText = sel.xpath('string(.)').get().strip()
    plainText = re.sub(r'\s+', '', plainText)    # 去掉空白
    # print('plainText: %s' % plainText)
    return plainText

def FnRepl(matched):
    r""" re.sub 的回调函数 """
    mathjaxFormula = matched.group(0)
    mathjaxFormula = mathjaxFormula[1:-1]  # 去掉前后的 $ 符号
    return Xml2PlainText(GetXml(mathjaxFormula))

def Convert(mathjaxText):
    plainText = re.sub('\$[\s\S]+?\$', FnRepl, mathjaxText)
    plainText = re.sub(r'\s+', ' ', plainText)    # 将多余空白替换成单个空格
    return plainText

if __name__ == '__main__':
    mathjaxText = 'Global well-posedness for the $L^2$-critical Hartree  equation on $\mathbb{R}^n$, $n\ge 3$'
    plainText = Convert(mathjaxText)
    print('mathjaxText: %s' % mathjaxText)
    print('plainText: %s' % plainText)

【相关阅读】

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019/09/25 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档