将大模型输出答案清洗数学公式格式为markdown文件

需求

大模型输出的答案中,通常公式格式为latex格式,无法直接在markdown中显示。因此需要:

将LaTeX的块级公式标识符\[...\]替换为Markdown的`$$...$$`,
行内公式标识符`\(...\)`替换为Markdown的`$...$`。

以下代码可以实现上述功能。

思路

  1. 读取markdown文件
  2. 使用正则表达式匹配公式内容—使用re库
  3. 进行替换—使用re.sub函数
  4. 输出新的markdown内容

代码内容

import re
from pathlib import Path


def convert_latex_to_markdown(text):
    # 替换块级公式 $$...$$ 为 $$...$$
    text = re.sub(r"\\\[(.*?)\\\]", r'$$\1$$', text, flags=re.DOTALL)
    # 替换行内公式 $...$ 为 $...$
    text = re.sub(r"\\\((.*?)\\\)", r'$\1$', text, flags=re.DOTALL)
    return text


def process_markdown_file(input_path, output_path=None):
    # 读取原始文件
    with open(input_path, 'r', encoding='utf-8') as f:
        original_content = f.read()

    # 转换内容
    converted_content = convert_latex_to_markdown(original_content)

    # 生成输出路径
    if not output_path:
        input_file = Path(input_path)
        output_path = input_file.parent / f"{input_file.stem}_converted{input_file.suffix}"

    # 写入新文件
    with open(output_path, 'w', encoding='utf-8') as f:
        f.write(converted_content)

    return output_path

if __name__ == "__main__":
    input_path = 'new.md'
    output_path = 'output.md'
    output_path = process_markdown_file(input_path, output_path)
    print(f"Conversion complete! New file saved at: {output_path}")

说明

在 Python 的re模块中,re.DOTALL是一个标志(flag),用于修改正则表达式的行为。它的作用是让点号(.)匹配任何字符,包括换行符(\n)。

默认情况下:

  • 在正则表达式中,点号(.)通常匹配任何字符,但不包括换行符。例如,.*会匹配任意字符(除换行符外),直到遇到换行符为止。

使用re.DOTALL

  • 当使用re.DOTALL标志时,点号(.)会匹配任何字符,包括换行符。这意味着正则表达式可以跨多行匹配内容。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值