自动将任意大文件分割并转换成单独Markdown文件

发布于 5 小时前  17 次阅读


本文于 2026年4月22日 2:48 更新,注意查看最新内容

前言

本文是前文的衍生篇,因为之前将其他软件自己的数据全部导了出来,于是又需要将自己的数据导入到其他的软件中,这时候我观察到该软件支持md文件的导入,便有了将整个数据文件分割并转换成单独md文件的想法,这里简单记录,以备日后查阅。

方法

1.将需要处理的数据以txt的文件保存。

2.将下列代码以py文件格式保存。

import os
import re

def split_content(content):
    # 使用正则按日期时间行拆分内容
    pattern = r"\n(?=\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})"
    parts = re.split(pattern, content)
    # 如果第一部分不是以日期开头,则丢弃(可能是文件开头的空行)
    if parts and not re.match(r"\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}", parts[0]):
        parts = parts[1:]
    return parts

def create_markdown_files(parts, output_dir="diaries"):
    os.makedirs(output_dir, exist_ok=True)
    count = 0
    for part in parts:
        lines = part.strip().split('\n', 1)
        time_title = lines[0].strip()           # 第一行是时间
        body = lines[1].strip() if len(lines) > 1 else ""
        
        # 处理文件名中的非法字符(Windows 不允许冒号等)
        safe_time = re.sub(r'[\\/*?:"<>|]', "", time_title).replace(" ", "_")
        filename = f"{safe_time}.md"            # 文件名只保留时间,无序号
        filepath = os.path.join(output_dir, filename)
        
        with open(filepath, 'w', encoding='utf-8') as f:
            f.write(body)                       # 内容只写正文,不写时间标题
        
        count += 1
        print(f"已生成: {filepath}")
    print(f"\n✅ 完成!共生成 {count} 个 Markdown 文件。")

if __name__ == "__main__":
    input_file = input("请将 txt 文件拖入此窗口,然后按回车:").strip('"')
    
    # 自动尝试多种常见编码,解决乱码问题
    encodings = ['utf-8', 'gbk', 'gb2312', 'ansi']
    content = None
    for enc in encodings:
        try:
            with open(input_file, "r", encoding=enc) as f:
                content = f.read()
            break
        except (UnicodeDecodeError, LookupError):
            continue
    
    if content is None:
        print("❌ 无法识别文件编码,请用记事本打开 txt 文件,另存为 UTF-8 编码后再试。")
    else:
        parts = split_content(content)
        create_markdown_files(parts)
    
    input("\n按回车键退出...")

*该代码由AI编写

3.双击第二步保存的py文件打开一个命令窗口,将需要处理的txt文件拖入并回车。此时运行py文件的的目录下会生成一个diaries文件夹,里面有所有处理好的单文件。

PS:上述步骤默认本地已部署Python环境。

关于异常的处理:

如果拖入txt文件回车后黑窗口一闪而过,看不到任何提示信息,本地也没有对应目录和单文件。

可以将下列代码保存为bat文件后运行:

python split_diary.py 
pause

PS:split_diary.py为上述第二步中你保存py文件的文件名。

后话

本文没法拿来直接使用,包括之后我自己再次查阅也没法直接使用,因为下次处理的数据未必就是上述代码的格式,但万变不离其宗,将上述代码和对应格式的数据发给Ai,便可以轻松生成可以使用的代码。