You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

62 lines
2.5 KiB

4 weeks ago
import re
import subprocess
import os
import uuid
4 weeks ago
4 weeks ago
# 获取MathType对应的Latex公式
def get_latex_list(docx_file):
# 获取当前目录的父级目录
current_dir = os.path.dirname(os.path.abspath(__file__))
current_dir = os.path.dirname(current_dir)
mtef = os.path.join(current_dir, 'mtef-go-3', 'mtef-go.exe')
res = []
output = os.path.join(os.environ['TEMP'], uuid.uuid4().hex + '.txt')
command = mtef + r" -w " + docx_file + " -o " + output
os.system(command)
with open(output, 'r', encoding='utf-8') as file:
for i, line in enumerate(file):
res.append(line.strip())
return res
4 weeks ago
4 weeks ago
# 结合Pandoc和mtef-go的结果合并成最终的输出文本
def get_docx_content_by_pandoc(docx_file):
# 一、获取Latex公式列表
formula_list = get_latex_list(docx_file)
4 weeks ago
# 最后拼接的内容
content = ""
4 weeks ago
# output_file 设置为临时目录下的uuid.md
temp_markdown = os.path.join(os.environ['TEMP'], uuid.uuid4().hex + '.md')
# 调用pandoc将docx文件转换成markdown
subprocess.run(['pandoc', docx_file, '-f', 'docx', '-t', 'markdown', '-o', temp_markdown])
4 weeks ago
# 打印 temp_markdown 文件
# with open(temp_markdown, 'r', encoding='utf-8') as f:
# print(f.read())
4 weeks ago
# 读取然后修改内容,输出到新的文件
4 weeks ago
wmf_idx = 0 # wmf索引
img_idx = 0 # 图片索引
with open(temp_markdown, 'r', encoding='utf-8') as f:
for line in f:
4 weeks ago
if line.strip():
# 改进后的正则表达式匹配更多格式的MathType公式
4 weeks ago
"""
![](media/image1.wmf)
问题2 氢气与氧气燃烧的方程式
.![](media/image2.wmf).
问题3 我是一个图片
![](media/image3.png){width="3.1251607611548557in" height="3.694634733158355in"}
"""
if line.index("![](media/image") >= 0 and line.index(".wmf") > 0:
content = content + formula_list[wmf_idx] + "\n"
wmf_idx = wmf_idx + 1
elif line.index("![](media/image") >= 0 and (
line.index(".png") > 0 or line.index(".jpg") > 0 or line.index(".jpeg") > 0):
content = content + "【图片" + str(img_idx) + "\n"
4 weeks ago
else:
4 weeks ago
content = content + line.strip() + "\n"
4 weeks ago
# 删除临时文件 output_file
os.remove(temp_markdown)
4 weeks ago
return content