当前位置: 首页 > news >正文

HTML 如何转 Markdown

标注:将多个 HTML 文件转换后合并到一个 .md 文件中

python代码附带如下:(使用下面代码轻松转)

from markdownify import markdownify as md
import os
from pathlib import Path
import chardetdef detect_file_encoding(file_path):"""检测文件编码:param file_path: 文件路径:return: 检测到的编码"""with open(file_path, 'rb') as f:raw_data = f.read(10000)result = chardet.detect(raw_data)return result['encoding']def convert_html_to_markdown(html_file_path):"""转换HTML文件为Markdown(自动处理编码):param html_file_path: HTML文件路径:return: (是否成功, 转换后的Markdown内容或错误信息)"""try:encoding = detect_file_encoding(html_file_path)if not encoding:encoding = 'euc-jp'with open(html_file_path, 'r', encoding=encoding, errors='replace') as f:html_content = f.read()# 转换为 Markdown,去掉加粗和斜体的标记markdown_content = md(html_content, strong_em_symbol='', em_symbol='')# 3.1 如果包含特定内容则移除if 'General - Move/Set - MOV' in markdown_content:markdown_content = markdown_content.replace('General - Move/Set - MOV', '')return (True, markdown_content)except UnicodeDecodeError:encodings_to_try = ['gb2312', 'gbk', 'gb18030', 'euc-jp', 'shift_jis', 'utf-8']for enc in encodings_to_try:try:with open(html_file_path, 'r', encoding=enc) as f:html_content = f.read()markdown_content = md(html_content, strong_em_symbol='', em_symbol='')if 'General - Move/Set - MOV' in markdown_content:markdown_content = markdown_content.replace('General - Move/Set - MOV', '')return (True, markdown_content)except:continuereturn (False, f"无法解码文件: {html_file_path}")except Exception as e:return (False, f"转换失败 {html_file_path}: {str(e)}")def batch_convert_html_to_md(input_dir, output_dir=None):"""批量转换目录下的HTML文件为Markdown,并合并为一个md文件:param input_dir: HTML文件所在目录:param output_dir: 输出目录"""if output_dir is None:output_dir = input_diros.makedirs(output_dir, exist_ok=True)merged_md_path = os.path.join(output_dir, "all_in_one.md")# 清空合并输出文件with open(merged_md_path, 'w', encoding='utf-8') as f:f.write("# 合并文档\n\n")stats = {'total': 0,'success': 0,'failed': 0,'encodings': {}}for root, _, files in os.walk(input_dir):for filename in files:if filename.lower().endswith(('.htm', '.html')):stats['total'] += 1html_path = os.path.join(root, filename)print(f"正在处理: {html_path}")success, result = convert_html_to_markdown(html_path)if success:stats['success'] += 1encoding = detect_file_encoding(html_path)stats['encodings'][encoding] = stats['encodings'].get(encoding, 0) + 1with open(merged_md_path, 'a', encoding='utf-8') as f:# f.write(f"\n\n## 来自文件: {filename}\n\n")name_without_ext = Path(filename).stem  # 去掉 .htm/.html 扩展名f.write(f"\n\n## {name_without_ext}\n\n")f.write(result)f.write("\n\n---\n\n")else:stats['failed'] += 1print(f"错误: {result}")print("\n=== 转换结果汇总 ===")print(f"总文件数: {stats['total']}")print(f"成功: {stats['success']}")print(f"失败: {stats['failed']}")print("\n编码分布:")for enc, count in stats['encodings'].items():print(f"{enc or '未知'}: {count} 个文件")print(f"\n输出文件: {os.path.abspath(merged_md_path)}")if __name__ == "__main__":input_directory = r"D:\\YH_Project\\html@md\\html file"         # 替换为你的 HTML 目录output_directory = r"D:\\YH_Project\\html@md\\markdown_output"  # 替换为输出目录batch_convert_html_to_md(input_directory, output_directory)

1. 首先要有python的环境

  1. 安装python(手动补上环境变量)
  2. 执行python包:pip install markdownify chardet

2. 准备输入输出目录(HTML或者HTM文件)

1. 在你电脑上准备一个文件夹,里面放几个 .html 或 .htm 文件

比如:

makefileD:\test_htmls\
2. 再准备一个输出文件夹(Markdown 会写到这):
makefileD:\test_markdown_output\

3. 使用方法

1. 编辑脚本末尾的路径:

找到下面两行,把路径替换为你本地的目录路径:

pythoninput_directory = r"D:\\soft\\code\\py_code\\testpy\\2052\\2052"  # HTML文件所在目录
output_directory = r"D:\\soft\\code\\py_code\\testpy\\markdown_output"  # 输出Markdown目录
2. 运行脚本

用命令行运行这个 .py 脚本:

bashpython your_script_name.py

你会看到类似:

makefile正在处理: D:\test_htmls\sample.html
=== 转换结果汇总 ===
总文件数: 1
成功: 1
失败: 0
输出目录: D:\test_markdown_output

4. 输出结果

  • 会在 output_directory 中保留输入目录的结构;
  • 所有 .html 或 .htm 文件会被转换为 .md 文件;
  • 编码会自动检测处理,不容易出乱码;
  • 最后会打印汇总统计,比如成功/失败数量、使用的编码分布等。
http://www.lryc.cn/news/610753.html

相关文章:

  • 【qt5_study】2.使用Qt Designer构造UI界面(信号与槽)
  • 16核32G硬件服务器租用需要多少钱
  • 工业级 CAN 与以太网桥梁:串口服务器CAN通讯转换器深度解析(下)
  • 前端实用工具方法 —— 持续更新中...
  • GPT-5的诞生之痛:AI帝国的现实危机
  • 前端权限设计
  • 云手机的主要功能都包含哪些?
  • MoonBit 月兔 - 云和边缘计算 AI云原生编程语言及开发平台
  • LangChain入门:代理、链、索引
  • WIN QT libsndfile库编译及使用
  • 【教程】Unity AssetBundle 资源管理方法
  • STM32F407VET6学习笔记10:移植smallmodbus
  • 【LeetCode 热题 100】347. 前 K 个高频元素——(解法一)排序截取
  • Redis类型之String
  • 【npm 解决】---- TypeError: crypto.hash is not a function
  • GPS信号捕获尝试
  • 【机器学习深度学习】模型剪枝
  • Python包安全工程实践:构建安全可靠的Python生态系统
  • 【学习笔记】NTP时间同步验证
  • 期权定价全解析:从Black-Scholes到量子革命的金融基石
  • Linux 逻辑卷管理:LVM 原理与 Stratis、VDO 特性对比
  • 基于 Spring Boot 的小区人脸识别与出入记录管理系统实现
  • 力扣经典算法篇-43-全排列(经典回溯问题)
  • css3属性总结和浏览器私有属性
  • Python、Java、C#实现浮点型转换为转型
  • Mysql使用Canal服务同步数据->ElasticSearch
  • 电子秤利用Websocket做为Client向MES系统推送数据
  • 文件编译、调试及库制作
  • 跑yolov5的train.py时,ImportError: Failed to initialize: Bad git executable.
  • 前端实现Excel文件的在线预览效果