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

相关推荐
leonkay几秒前
C# 特性(Attribute)——【1】基础讲解
开发语言·青少年编程·面试·c#·.net·个人开发
harmful_sheep10 分钟前
java group by常见用法
java·开发语言·python
whcyhhh35 分钟前
头歌实践教学平台:数据科学与大数据技术导论(十六)
大数据·开发语言·python
宸津-代码粉碎机37 分钟前
AI工程化高阶实战|从Demo到生产落地核心架构、全套源码与避坑指南
java·大数据·开发语言·人工智能·python·架构
CSDN_RTKLIB1 小时前
数据库七大符号表
c#
leonkay2 小时前
C# 特性(Attribute)——【2】工业设备参数框架设计
经验分享·面试·架构·c#·学习方法·设计
郝学胜-神的一滴2 小时前
Effective Python 条款4:字符串格式化大乱斗
开发语言·网络·python·程序人生·软件工程
2501_906565122 小时前
小创 · 智能助手
开发语言·c#
ynchyong2 小时前
Python 字符组合生成器:product 与 permutations 的实战对比
python·工具·字符串生产
benchmark_cc2 小时前
1000只ETF的5分钟K线如何批量获取?QuantDash分页策略与高性能Python实践
开发语言·人工智能·爬虫·python·算法·quantdash·量化数据源