import re
from pathlib import Path

def clean_code_blocks_only(file_path, output_path):
    with open(file_path, 'r', encoding='utf-8') as f:
        content = f.read()

    # 匹配所有代码块，包括可能的语言标识，例如 ```python\n...\n```
    pattern = re.compile(r'```(\w*)\n(.*?)```', re.DOTALL)

    def clean_block(match):
        lang = match.group(1)
        code = match.group(2)
        # 去掉空行
        cleaned_code = "\n".join(
            line for line in code.splitlines() if line.strip() != ""
        )
        return f"```{lang}\n{cleaned_code}\n```"

    new_content = pattern.sub(clean_block, content)

    with open(output_path, 'w', encoding='utf-8') as f:
        f.write(new_content)

    print(f"✅ 代码块已清理，结果保存为: {output_path}")

# 使用示例
input_file = "merged.md"
output_file = "merged_cleaned.md"

clean_code_blocks_only(input_file, output_file)
