python实现Latex格式的公式转OMML并写入word

1. 字符串中只有公式

python 复制代码
from docx import Document
from latex2word import LatexToWordElement

def strip_double_dollar(s: str) -> str:
    """
    若字符串前后均有 '$$',则去掉它们;否则返回原字符串。
    """
    if s.startswith('$$') and s.endswith('$$') and len(s) >= 4:
        return s[2:-2]
    return s
latex_input = "$$ P_{R418} = \frac{(36/2)^2}{4.5kΩ} = 72mW $$"
latex_to_word = LatexToWordElement(latex_input)
doc = Document('demo_test.docx')
paragraph = doc.add_paragraph()
latex_to_word.add_latex_to_paragraph(paragraph)
doc.save('demo_test.docx')

运行结果:

2. markdown字符串转Word

markdown中存在公式、表格、图片链接、段落文字等信息
需要将markdown转为html再转为word进行保存

对公式相关的处理如下:

首先将markdown转为html,为了保证中间的''等字符不被解析掉,需要将其进行转换:

python 复制代码
import markdown
text = "$\\l_IH_max = 10/\\mu A$"
escaped = text.replace('$', '$').replace('\\', '\')
html = markdown.markdown(escaped, extensions=["tables", "fenced_code", "nl2br", "sane_lists", "extra"])
)

接下来分别针对html不同的标签,对element中的文本提取,然后进行doc文本的添加即可;

其中公式调用标题1中的代码即可实现;

相关推荐
2401_891450461 天前
Python上下文管理器(with语句)的原理与实践
jvm·数据库·python
helloworldandy1 天前
使用Python处理计算机图形学(PIL/Pillow)
jvm·数据库·python
FuckPatience1 天前
C# 对象初始化器对属性赋值vs构造函数里对属性赋值
c#
2301_790300961 天前
Python单元测试(unittest)实战指南
jvm·数据库·python
VCR__1 天前
python第三次作业
开发语言·python
韩立学长1 天前
【开题答辩实录分享】以《助农信息发布系统设计与实现》为例进行选题答辩实录分享
python·web
2401_838472511 天前
使用Scikit-learn构建你的第一个机器学习模型
jvm·数据库·python
u0109272711 天前
使用Python进行网络设备自动配置
jvm·数据库·python
工程师老罗1 天前
优化器、反向传播、损失函数之间是什么关系,Pytorch中如何使用和设置?
人工智能·pytorch·python
Fleshy数模1 天前
我的第一只Python爬虫:从Requests库到爬取整站新书
开发语言·爬虫·python