将markdown文件和LaTex公式转为word

embedded/2025/2/4 12:13:01/

通义千问等大模型生成的回答多数是markdown类型的,需要将他们转为Word文件

一 pypandoc 介绍

1. 项目介绍
pypandoc 是一个用于 pandoc 的轻量级 Python 包装器。pandoc 是一个通用的文档转换工具,支持多种格式的文档转换,如 Markdown、HTML、LaTeX、DocBook 等。pypandoc 通过提供一个简单的 Python 接口,使得在 Python 脚本中调用 pandoc 变得更加方便。

2. 安装

使用pip安装:
pip install pypandoc_binary
自动下载 Pandoc并安装
注意:pypandoc 提供了两个包:
pypandoc:需要用户自行安装 pandoc软件才能使用。
pypandoc_binary:包含了预编译的 pandoc 二进制文件,方便用户快速上手。

手动安装
可以手动安装pandoc再安装pypandoc库
pip install pypandoc
也可以先安装pypandoc然后再在pyhon中运行 pypandoc.download_pandoc()函数自动下载并安装 Pandoc,将其存放在 pypandoc 可以访问的目录中。

二、使用Python 将markdown转Word
本脚本实现了三类功能
1、将markdown文件转为word文件
2、将 markdown中段落开头的“-“转为回车,避免渲染成黑点或者空心圆等Word中不常见的符号
3、自定义了模板,格式化输出。

import pypandoc
import time
import re# 定义路径
path1 = r"md.md"
path2 = r".docx"
template_path = r"D:\aTools\ytemplates\templates_s.docx"# 读取原始Markdown文件内容
with open(path1, 'r', encoding='utf-8') as file:content = file.read()# 使用正则表达式将以'- '开头的部分替换为换行符
processed_content = re.sub(r'- ', '\n', content)# 记录开始时间
t1 = time.time()# 将处理后的内容转换为Word文档
pypandoc.convert_text(processed_content,'docx',format='md',outputfile=path2,extra_args=['--reference-doc', template_path]
)# 打印耗时
print(time.time() - t1)
print("转换完成!")

三、直接指定Word格式

直接读取文件(可以为txt或者md)转为指定格式的word
这里格式是:
1、将 markdown中段落开头的“-“转为回车,避免渲染成黑点或者空心圆等Word中不常见的符号
2、将原来加粗部分继续加粗和左对齐
3、字体为黑色GB2312

注意:代码用正则替换####这些时需要先从4级标题开始替换否则会有逻辑错误,导致奇数个#无法替换。

设置中文字体不能用run.font.name = '仿宋_GB2312’而是用style._element.rPr.rFonts.set(qn(‘w:eastAsia’), ‘仿宋_GB2312’) 设置中文字体。

import re
from docx import Document
from docx.shared import Pt, RGBColor
from docx.enum.text import WD_ALIGN_PARAGRAPH
from docx.oxml.ns import qn# 定义设置字体和颜色的函数
def set_font_color(run):run.font.name = 'Times New Roman'  # 设置西文字体run._element.rPr.rFonts.set(qn('w:eastAsia'), '仿宋_GB2312')  # 设置中文字体run.font.size = Pt(12)run.font.color.rgb = RGBColor(0, 0, 0)run.italic = False  # 去除斜体# 定义路径
path1 = r"C:\Users\xueshifeng\Desktop\数据分割.txt"
path2 = r"C:\Users\xueshifeng\Desktop\数据分割.docx"# 读取原始txt文件内容
with open(path1, 'r', encoding='utf-8') as file:content = file.read()# 处理以'- '开头的项目符号
processed_content = re.sub(r'- ', '\n', content)# 创建一个新的Word文档
doc = Document()# 设置默认字体为仿宋_GB2312
style = doc.styles['Normal']
style.font.name = 'Times New Roman'  # 设置西文字体
style._element.rPr.rFonts.set(qn('w:eastAsia'), '仿宋_GB2312')  # 设置中文字体
style.font.size = Pt(12)
style.font.color.rgb = RGBColor(0, 0, 0)# 正则表达式模式
bold_pattern = re.compile(r'\*\*(.*?)\*\*')
heading4_pattern = re.compile(r'^\s*####\s*(.*)')  # 四级标题
heading3_pattern = re.compile(r'^\s*###\s*(.*)')  # 三级标题
heading2_pattern = re.compile(r'^\s*##\s*(.*)')  # 二级标题
heading1_pattern = re.compile(r'^\s*#\s*(.*)')  # 一级标题# 处理每一行内容
for line in processed_content.split('\n'):# 检查四级标题heading_match = heading4_pattern.match(line)if heading_match:title_text = heading_match.group(1).strip()if title_text:heading = doc.add_heading(title_text, level=4)heading.alignment = WD_ALIGN_PARAGRAPH.LEFTfor run in heading.runs:set_font_color(run)run.bold = Truecontinue  # 跳过后续处理# 检查三级标题heading_match = heading3_pattern.match(line)if heading_match:title_text = heading_match.group(1).strip()if title_text:heading = doc.add_heading(title_text, level=3)heading.alignment = WD_ALIGN_PARAGRAPH.LEFTfor run in heading.runs:set_font_color(run)run.bold = Truecontinue  # 跳过后续处理# 检查二级标题heading_match = heading2_pattern.match(line)if heading_match:title_text = heading_match.group(1).strip()if title_text:heading = doc.add_heading(title_text, level=2)heading.alignment = WD_ALIGN_PARAGRAPH.LEFTfor run in heading.runs:set_font_color(run)run.bold = Truecontinue  # 跳过后续处理# 检查一级标题heading_match = heading1_pattern.match(line)if heading_match:title_text = heading_match.group(1).strip()if title_text:heading = doc.add_heading(title_text, level=1)heading.alignment = WD_ALIGN_PARAGRAPH.LEFTfor run in heading.runs:set_font_color(run)run.bold = Truecontinue  # 跳过后续处理# 处理普通段落和加粗文本matches = list(bold_pattern.finditer(line))if not matches:paragraph = doc.add_paragraph(line)paragraph.alignment = WD_ALIGN_PARAGRAPH.LEFTfor run in paragraph.runs:set_font_color(run)else:paragraph = doc.add_paragraph()start = 0for match in matches:if match.start() > start:run = paragraph.add_run(line[start:match.start()])set_font_color(run)run = paragraph.add_run(match.group(1))run.bold = Trueset_font_color(run)start = match.end()if start < len(line):run = paragraph.add_run(line[start:])set_font_color(run)paragraph.alignment = WD_ALIGN_PARAGRAPH.LEFT# 保存文档
doc.save(path2)print("转换完成!")

四、将LaTex公式转为Word

将 latex_content字符串$ $ 中间的位置替换为公式,或者直接复制代码到GPT,让GPT修改代码

import pypandoc# 定义包含特定公式的LaTeX字符串
#$ $ 中间的位置替换为公式,或者直接复制代码到GPT,让GPT生成最终代码
latex_content = r"""
\documentclass{article}
\usepackage{amsmath} % 确保包含用于数学排版的包
\begin{document}$ L(y_i, f(x_i)) = \max(0, 1 - y_if(x_i)) $\end{document}
"""# 将LaTeX内容转换为Word文档
output_file = r"xx14.docx"output = pypandoc.convert_text(latex_content,  # 输入的字符串'docx',         # 输出格式format='latex', # 输入格式(LaTeX)outputfile=output_file,  # 输出文件路径extra_args=['--mathml']  # 额外参数,确保公式渲染为MathML格式
)# 检查转换是否成功
if output != '':print(f"转换过程中出现错误: {output}")
else:print(f"Word 文档已生成: {output_file}")

http://www.ppmy.cn/embedded/159464.html

相关文章

WebForms SortedList 深度解析

WebForms SortedList 深度解析 引言 在Web开发领域,对于数据结构的理解与应用至关重要。其中,SortedList类在WebForms中是一个常用的数据结构,它能够帮助开发者高效地管理有序数据集合。本文将深入解析SortedList类在WebForms中的应用,包括其基本概念、常用方法、性能特点…

基于新一代电子电器架构的SOA服务设计方法

我是穿拖鞋的汉子&#xff0c;魔都中坚持长期主义的汽车电子工程师。 老规矩&#xff0c;分享一段喜欢的文字&#xff0c;避免自己成为高知识低文化的工程师&#xff1a; 简单&#xff0c;单纯&#xff0c;喜欢独处&#xff0c;独来独往&#xff0c;不易合同频过着接地气的生活…

计算机毕业设计Python动漫推荐系统 漫画推荐系统 动漫视频推荐系统 机器学习 bilibili动漫爬虫 数据可视化 数据分析 大数据毕业设计

温馨提示&#xff1a;文末有 CSDN 平台官方提供的学长联系方式的名片&#xff01; 温馨提示&#xff1a;文末有 CSDN 平台官方提供的学长联系方式的名片&#xff01; 温馨提示&#xff1a;文末有 CSDN 平台官方提供的学长联系方式的名片&#xff01; 作者简介&#xff1a;Java领…

软件工程概论试题五

一、多选 1.好的软件的基本属性包括()。 A. 效率 B. 可依赖性和信息安全性 C. 可维护性 D.可接受性 正答&#xff1a;ABCD 2.软件工程的三要素是什么()? A. 结构化 B. 工具 C.面向对象 D.数据流! E.方法 F.过程 正答&#xff1a;BEF 3.下面中英文术语对照哪些是正确的、且是属…

CommonJS

CommonJS 是由 JavaScript 社区于 2oo9 年提出的包含模块、文件、IO、控制台在内的一系列标准。Node.js 的实现中采用了 CommonJS 标准的一部分&#xff0c;并在其基础上进行了一些调整。我们所说的 CommonJS 模块和 Node.js 中的实现并不完全一样&#xff0c;现在一般谈到 Com…

mysqldump+-binlog增量备份

注意&#xff1a;二进制文件删除必须使用help purge 不可用rm -f 会崩 一、概念 增量备份&#xff1a;仅备份上次备份以后变化的数据 差异备份&#xff1a;仅备份上次完全备份以后变化的数据 完全备份&#xff1a;顾名思义&#xff0c;将数据完全备份 其中&#xff0c;…

19.Word:小马-校园科技文化节❗【36】

目录 题目​ NO1.2.3 NO4.5.6 NO7.8.9 NO10.11.12索引 题目 NO1.2.3 布局→纸张大小→页边距&#xff1a;上下左右插入→封面&#xff1a;镶边→将文档开头的“黑客技术”文本移入到封面的“标题”控件中&#xff0c;删除其他控件 NO4.5.6 标题→原文原文→标题 正文→手…

爬虫基础(六)代理简述

目录 一、什么是代理 二、基本原理 三、代理分类 一、什么是代理 爬虫一般是自动化的&#xff0c;当我们自动运行时 爬虫自动抓取数据&#xff0c;但一会就出现了错误&#xff1a; 如&#xff0c;您的访问频率过高&#xff01; 这是因为网站的反爬措施&#xff0c;如果频…