Python:将指定的html转换成markdown
·
Python:将指定的html转换成markdown
import argparse
import html2text
import os
def html_to_markdown(input_file, output_file=None):
"""
将 HTML 文件转换为 Markdown 文件
Args:
input_file (str): 输入的 HTML 文件路径
output_file (str, optional): 输出的 Markdown 文件路径。如果未提供,将使用输入文件名,扩展名改为 .md
"""
# 检查输入文件是否存在
if not os.path.exists(input_file):
raise FileNotFoundError(f"输入文件不存在: {input_file}")
# 确定输出文件名
if output_file is None:
output_file = os.path.splitext(input_file)[0] + '.md'
# 读取 HTML 内容
with open(input_file, 'r', encoding='utf-8') as f:
html_content = f.read()
# 创建 HTML 到 Markdown 转换器
h = html2text.HTML2Text()
h.ignore_links = False
h.ignore_images = False
# 转换 HTML 到 Markdown
markdown_content = h.handle(html_content)
# 写入 Markdown 文件
with open(output_file, 'w', encoding='utf-8') as f:
f.write(markdown_content)
print(f"转换完成: {input_file} -> {output_file}")
if __name__ == "__main__":
# 设置命令行参数
parser = argparse.ArgumentParser(description='将 HTML 文件转换为 Markdown 文件')
parser.add_argument('input', help='输入的 HTML 文件路径')
parser.add_argument('-o', '--output', help='输出的 Markdown 文件路径(可选)')
args = parser.parse_args()
try:
html_to_markdown(args.input, args.output)
except Exception as e:
print(f"错误: {e}")
更多推荐


所有评论(0)