有没有办法使用python生成带有方程和公式的word文档? 现在,我正在使用 python-docx 来生成 Word 文档。我检查了 python-docx 的文档,但没有找到任何与公式和方程相关的内容。
我需要从Word文档中提取公式,并使用提取的公式生成一个新的Word文档。
是否可以在Python中从Word文档中提取方程并将其存储在数据库或其他东西中,然后用该公式和方程生成Word文档???
编辑:我附上了一些我需要提取/生成的方程
这里是如何使用 MathML 字符串中的方程生成 MS Word 文档的代码。
注意:您将需要
MML2OMML.XSL
文件,您可以在 MS Office 发行版中找到该文件,例如:在 C:\Program Files\Microsoft Office\root\Office16\MML2OMML.XSL
中。
from docx import Document
from lxml import etree
# MathML representation of "(x+y)²"
mathml_string = """
<math xmlns="http://www.w3.org/1998/Math/MathML">
<msup>
<mrow>
<mfenced>
<mrow>
<mi>x</mi>
<mo>+</mo>
<mi>y</mi>
</mrow>
</mfenced>
</mrow>
<mn>2</mn>
</msup>
</math>
"""
# parse XML from MathML string content
mathml_tree = etree.fromstring(mathml_string)
# convert MathML to Office MathML (OMML) using XSLT
# NOTE: You can find "MML2OMML.XSL" in the MS Office distribution, e.g.: "C:\Program Files\Microsoft Office\root\Office16\MML2OMML.XSL"
xslt = etree.parse('MML2OMML.XSL')
transform = etree.XSLT(xslt)
omml_tree = transform(mathml_tree)
# Serialize the Office MathML (OMML) to a string
omml_string = etree.tostring(omml_tree, pretty_print=True, encoding="unicode")
# Write to Word document
document = Document()
p = document.add_paragraph()
# Append the converted OMML to the paragraph
p._element.append(omml_tree.getroot()) # Append the root element of the OMML tree
# Save the document
document.save("simpleEq_with_Formula.docx")
受到 StackOF 上其他答案的启发。