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

相关推荐
极客小云7 分钟前
【ComfyUI API 自动化利器:comfyui_xy Python 库使用详解】
网络·python·自动化·comfyui
啦啦啦_999919 分钟前
Redis-5-doFormatAsync()方法
数据库·redis·c#
闲人编程23 分钟前
Elasticsearch搜索引擎集成指南
python·elasticsearch·搜索引擎·jenkins·索引·副本·分片
痴儿哈哈32 分钟前
自动化机器学习(AutoML)库TPOT使用指南
jvm·数据库·python
花酒锄作田1 小时前
SQLAlchemy中使用UPSERT
python·sqlalchemy
SoleMotive.1 小时前
一个准程序员的健身日志:用算法调试我的增肌计划
python·程序员·健身·职业转型
亓才孓1 小时前
[Properties]写配置文件前,必须初始化Properties(引用变量没执行有效对象,调用方法会报空指针错误)
开发语言·python
Bruk.Liu1 小时前
(LangChain 实战14):基于 ChatMessageHistory 自定义实现对话记忆功能
人工智能·python·langchain·agent
Porco.w1 小时前
C#与三菱PLC FX5U通信
网络·c#
大江东去浪淘尽千古风流人物1 小时前
【VLN】VLN(Vision-and-Language Navigation视觉语言导航)算法本质,范式难点及解决方向(1)
人工智能·python·算法