需求
大模型输出的答案中,通常公式格式为latex格式,无法直接在markdown中显示。因此需要:
将LaTeX的块级公式标识符\[...\]替换为Markdown的`$$...$$`,
行内公式标识符`\(...\)`替换为Markdown的`$...$`。
以下代码可以实现上述功能。
思路
- 读取markdown文件
- 使用正则表达式匹配公式内容—使用re库
- 进行替换—使用re.sub函数
- 输出新的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_pat

最低0.47元/天 解锁文章
279

被折叠的 条评论
为什么被折叠?



