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

相关推荐
用户8356290780517 小时前
使用 Python 自动化 PowerPoint 形状布局与格式设置
后端·python
Scout-leaf7 小时前
C#摸鱼实录——IoC与DI案例详解
c#
用户8356290780519 小时前
用 Python 自动化 PowerPoint 演讲者备注添加
后端·python
咕白m6259 小时前
使用 C# 在 Excel 中应用多种字体样式
后端·c#
黄忠14 小时前
01-系统架构设计-LangGraph状态机与多源异构RAG
python
zzzzzz31014 小时前
假如我是掘金管理员,我先给评论区装个'代码审查'系统
python·程序员·机器人
Artech15 小时前
[MAF预定义的AIContextProvider-02]AgentSkillsProvider——将Agent Skills引入MAF
ai·c#·agent·agent skills·maf
砍材农夫15 小时前
python环境|conda安装和使用(2)
后端·python
程序员龙叔1 天前
编写高质量 Skill 系列 -- 如何设计需求分析与用例生成的 SKILL
自动化测试·软件测试·python·软件测试工程师·接口测试·性能测试·skill·ai测试
用户8356290780511 天前
使用 Python 操作 Word 内容控件
后端·python