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中的代码即可实现;

相关推荐
日日大王学编程4 小时前
DeepSeekHarness开源Agent底座详解
python·开源·deep learning
Eider19984 小时前
python基础语法之并发基础练习
开发语言·python
长和信泰光伏储能4 小时前
探索绿色能源:光伏发电的渠道与应用
python·能源
郝学胜-神的一滴4 小时前
AI 编程智能体 20:技术栈选型与架构落地全攻略
人工智能·python·架构·langchain·1024程序员节·智能体
云和数据.ChenGuang4 小时前
python和java的try
java·开发语言·python
小小张说故事5 小时前
Python 的 list 为什么能装下任何类型?拆开 PyObject* 数组,以及它让你多付了多少内存
后端·python
chi11305 小时前
【无标题】
前端·javascript·python
编程见习者5 小时前
Deep Agents介绍
人工智能·python·langchain
梦幻精灵_cq5 小时前
《SGR修行之路》——二○二一五二〇,初识终端点红裳
python·生活
我要见SA姐15 小时前
Chrome 内存泄漏诊断指南:从现象定位到根因排查
ide·vscode·python·自动化·编辑器