Typora使用处理的一些小技巧

Typora使用处理的一些小技巧

一、合并指定路径下的所有.md文件

环境支持

需要以下环境:
  • Python 3.x
  • Windows、macOS 或 Linux 操作系统
  • 指定的文件夹路径存在且包含 .md 文件
  • 文件编码为 UTF-8 或 GBK
  • 对文件夹和文件有读写权限
1. Python 环境
  • Python 版本:代码中使用了 os 模块和文件操作,这些功能在 Python 3.x 中都能正常运行,因此需要安装 Python 3.x(例如 Python 3.7、3.8、3.9 等)。不建议使用 Python 2.x,因为 Python 2 已经停止支持。
  • 安装方式:可以从 Python 官方网站 下载并安装 Python。
2. 操作系统支持
  • 代码使用了 os 模块来操作文件路径,因此可以在 Windows、macOS 和 Linux 等主流操作系统上运行。不过,需要注意路径格式:
    • 在 Windows 系统中,路径格式如代码中所示:r"D:\桌面文件所在处\2026考研资料\WD数据结构笔记"
    • 在 macOS 或 Linux 系统中,路径格式会有所不同,例如:/Users/username/Desktop/2026考研资料/WD数据结构笔记
3. 文件夹和文件要求
  • 目标文件夹存在:代码会检查指定的文件夹路径是否存在,如果不存在会提示错误。因此,需要确保指定的文件夹路径是正确的,并且该文件夹中包含 .md 格式的 Markdown 文件。
  • Markdown 文件存在:文件夹中需要有 .md 文件,否则会提示“未找到 Markdown 文件”。
  • 输出文件名:默认输出文件名为 all.md,如果文件夹中已经存在同名的 all.md 文件,可能会导致覆盖。如果不想覆盖,可以修改代码中的 output_file_name 参数。
4. 文件编码
  • 代码尝试以 UTF-8 编码读取 Markdown 文件,如果文件编码不是 UTF-8,会尝试使用 GBK 编码读取。如果文件编码既不是 UTF-8 也不是 GBK,可能会导致读取失败。因此,需要确保目标文件的编码是 UTF-8 或 GBK,或者根据实际情况调整代码中的编码方式。
5. 权限要求
  • 需要对目标文件夹和文件有读写权限,否则可能会出现权限错误,导致无法读取文件或写入输出文件。

源码

import os

def merge_markdown_files(folder_path, output_file_name="all.md"):
    # 检查文件夹是否存在
    if not os.path.exists(folder_path):
        print(f"指定的文件夹路径不存在:{folder_path}")
        return

    # 获取文件夹下所有Markdown文件
    markdown_files = [f for f in os.listdir(folder_path) if f.endswith('.md') and f != output_file_name]

    if not markdown_files:
        print("未找到Markdown文件,或所有Markdown文件已合并到输出文件中。")
        return

    # 创建输出文件的完整路径
    output_file_path = os.path.join(folder_path, output_file_name)

    try:
        # 打开输出文件
        with open(output_file_path, 'w', encoding='utf-8') as output_file:
            # 遍历每个Markdown文件并将其内容写入输出文件
            for md_file in markdown_files:
                file_path = os.path.join(folder_path, md_file)
                try:
                    with open(file_path, 'r', encoding='utf-8') as input_file:
                        content = input_file.read()
                        output_file.write(content)
                        output_file.write("\n\n")  # 在每个文件内容之间添加空行
                except UnicodeDecodeError:
                    print(f"文件 {md_file} 编码不是 UTF-8,尝试使用其他编码读取...")
                    try:
                        with open(file_path, 'r', encoding='gbk') as input_file:
                            content = input_file.read()
                            output_file.write(content)
                            output_file.write("\n\n")  # 在每个文件内容之间添加空行
                    except UnicodeDecodeError:
                        print(f"无法读取文件 {md_file},请检查文件编码。")

        print(f"所有Markdown文件已成功合并到 {output_file_path}")
    except Exception as e:
        print(f"合并过程中发生错误:{e}")

# 使用示例
# 替换为你的文件夹路径,注意路径格式
folder_path = r"D:\桌面文件所在处"
merge_markdown_files(folder_path)

运行

  • 将代码复制到一个文本编辑器(windows自带也可)中(例如 Notepad++、VS Code 或其他支持 Python 的编辑器)。
  • 将文件保存为 .py 扩展名,例如 merge_markdown.py

二、提取markdown文件中LaTeX 公式出来,将其转换为图片

将 Markdown 文件中的 LaTeX 公式提取出来,将其转换为图片,并将公式替换为图片引用,最终保存为一个新的 Markdown 文件

所需环境和工具:

1. Python 环境
  • Python 版本:需要 Python 3.x(例如 Python 3.7、3.8、3.9 等)。
  • 安装方式:可以从 Python 官方网站 下载并安装 Python。
2. LaTeX 环境
  • 安装 LaTeX:需要一个完整的 LaTeX 发行版,例如 TeX LiveMiKTeX

    • TeX Live:适用于 Linux 和 macOS 系统。
    • MiKTeX:适用于 Windows 系统。
  • 确保 pdflatex 命令可用:安装完成后,需要确保 pdflatex 命令可以在命令行中直接运行。可以通过在命令行中运行以下命令来测试:

    pdflatex --version
    

    如果提示“命令未找到”,需要将 LaTeX 的安装路径添加到系统的环境变量中。

3. ImageMagick
  • 安装 ImageMagick:用于将 PDF 文件转换为 PNG 图片。

    • Windows:可以从 ImageMagick 官方网站 下载安装程序。

    • macOS:可以通过 Homebrew 安装:

      brew install imagemagick
      
    • Linux:可以通过包管理器安装,例如:

      sudo apt-get install imagemagick
      
  • 确保 magick 命令可用:安装完成后,需要确保 magick 命令可以在命令行中直接运行。可以通过在命令行中运行以下命令来测试:

    magick --version
    

    并确保文件的编码格式为 UTF-8。

源码

import re
import os
import subprocess

# 读取 Markdown 文件
with open('example.md', 'r', encoding='utf-8') as file:
    content = file.read()

# 提取公式
# 支持多行公式,使用 re.DOTALL 使 . 匹配换行符
formulas = re.findall(r'\$\$([\s\S]+?)\$\$', content, re.DOTALL)
formulas.extend(re.findall(r'\$([^$]+)\$', content))

# 为每个公式生成 LaTeX 文件并转换为图片
for i, formula in enumerate(formulas):
    tex_file = f'formula{i+1}.tex'
    pdf_file = f'formula{i+1}.pdf'
    png_file = f'formula{i+1}.png'

    # 创建 LaTeX 文件
    with open(tex_file, 'w', encoding='utf-8') as tex:
        tex.write(f'''\\documentclass{{article}}
\\usepackage{{amsmath}}
\\pagestyle{{empty}} % 禁用页码
\\begin{{document}}
\\[
{formula.strip()}
\\]
\\end{{document}}
''')

    # 使用 pdflatex 转换为 PDF
    try:
        subprocess.run(['pdflatex', '-interaction=nonstopmode', tex_file], check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
        # 删除 LaTeX 文件
        os.remove(tex_file)
    except subprocess.CalledProcessError as e:
        print(f"Warning: Error converting {tex_file} to PDF: {e}")
        # 检查 PDF 文件是否生成
        if not os.path.exists(pdf_file):
            print(f"PDF file {pdf_file} was not generated. Skipping conversion to PNG.")
            continue

    # 使用 ImageMagick 转换为 PNG
    try:
        subprocess.run(['magick', '-density', '300', pdf_file, '-trim', '-quality', '100', png_file], check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
        # 删除 PDF 文件
        os.remove(pdf_file)
    except subprocess.CalledProcessError as e:
        print(f"Error converting {pdf_file} to PNG: {e}")
        continue

    # 清理其他临时文件
    for ext in ['.log', '.aux']:
        temp_file = f'{pdf_file[:-4]}{ext}'
        if os.path.exists(temp_file):
            os.remove(temp_file)

    # 替换公式为缩放后的图片引用
    img_tag = f'<img src="{png_file}"  alt="formula{i+1}" style="zoom:50%;">'
    content = content.replace(f'$$\n{formula}\n$$', img_tag)
    content = content.replace(f'${formula}$', img_tag)

# 保存修改后的 Markdown 文件为一个新的文件
output_file = 'example_with_images.md'
with open(output_file, 'w', encoding='utf-8') as file:
    file.write(content)

print(f"公式转换完成!修改后的内容已保存到 {output_file}")
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值