当前位置: 首页 > news >正文

将markdown文件和LaTex公式转为word

通义千问等大模型生成的回答多数是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.lryc.cn/news/530617.html

相关文章:

  • grpc 和 http 的区别---二进制vsJSON编码
  • C#面向对象(封装)
  • kamailio-kamctl monitor解释
  • 39. I2C实验
  • GPIO配置通用输出,推挽输出,开漏输出的作用,以及输出上下拉起到的作用
  • Spring AOP 入门教程:基础概念与实现
  • DeepSeek 核心技术全景解析
  • 90,【6】攻防世界 WEB Web_php_unserialize
  • 实现网站内容快速被搜索引擎收录的方法
  • WSL2中安装的ubuntu搭建tftp服务器uboot通过tftp下载
  • 机器学习优化算法:从梯度下降到Adam及其变种
  • [SAP ABAP] 静态断点的使用
  • 129.求根节点到叶节点数字之和(遍历思想)
  • NCCL、HCCL、通信、优化
  • unity学习21:Application类与文件存储的位置
  • 17 一个高并发的系统架构如何设计
  • Spring Boot 实例解析:配置文件
  • pytorch图神经网络处理图结构数据
  • 计算机网络一点事(23)
  • (9)下:学习与验证 linux 里的 epoll 对象里的 EPOLLIN、 EPOLLHUP 与 EPOLLRDHUP 的不同。小例子的实验
  • DeepSeek-R1模型1.5b、7b、8b、14b、32b、70b和671b有啥区别?
  • 一、html笔记
  • AI大模型开发原理篇-2:语言模型雏形之词袋模型
  • 基于微信小程序的实习记录系统设计与实现(LW+源码+讲解)
  • 【LLM】DeepSeek-R1-Distill-Qwen-7B部署和open webui
  • 【Elasticsearch】 Intervals Query
  • DeepSeek技术深度解析:从不同技术角度的全面探讨
  • Docker 部署 Starrocks 教程
  • 【LLM-agent】(task6)构建教程编写智能体
  • 29.Word:公司本财年的年度报告【13】