基于Python实现HTML转Markdown格式的小工具

 更新时间:2025年07月10日 09:47:33   作者:Kyln.Wu  
在现代文档处理和内容创作中,HTML 和 Markdown 是两种广泛使用的格式,本文将介绍一个基于 Python 的 HTML 到 Markdown 转换工具,希望对大家有所帮助

引言

在现代文档处理和内容创作中,HTML 和 Markdown 是两种广泛使用的格式。HTML 是网页的标准标记语言,而 Markdown 是一种轻量级的标记语言,常用于编写易于阅读和书写的文档。在某些情况下,用户可能需要将 HTML 文件转换为 Markdown 格式,例如在迁移到静态网站生成器或需要简化文档格式时。本文将介绍一个基于 Python 的 HTML 到 Markdown 转换工具,它能够自动化地将 HTML 文件转换为 Markdown 文件。该工具主要利用了 Python 的 markdownify 库和 tkinter 库,结合了格式转换和图形用户界面设计,为用户提供了一个简单易用的解决方案。

总体功能概述

HTML 到 Markdown 转换工具是一个 Python 应用程序,其核心功能是将指定的 HTML 文件转换为 Markdown 文件。它通过调用 markdownify 库来实现格式转换,并利用 tkinter 库构建了一个直观的图形用户界面(GUI),使用户能够轻松选择文件并执行转换操作。此外,工具还提供了文件路径验证和错误处理功能,确保转换过程的稳定性和可靠性。

图形用户界面设计

为了使工具易于使用,我们采用了 Python 的 tkinter 库来构建图形用户界面。以下是界面设计的代码片段及解析:

from tkinter import Tk, END, Frame, SUNKEN, Label
from tkinter import font, Button, X, Entry, Text, BOTH
from PIL import ImageTk, Image

root = Tk(className=" ALHTMLTOMARKDOWN ")
root.geometry("400x175+1500+840")
root.resizable(0, 0)
root.iconbitmap(os.path.join(cwd + '\\UI\\icons', 'alhtmltomarkdown.ico'))
root.config(bg="#6a199b")

在上述代码中,Tktkinter 的主窗口类,用于创建应用程序的主窗口。geometry 方法用于设置窗口的大小和位置,resizable 方法用于禁止窗口大小调整,iconbitmap 方法用于设置窗口图标。窗口的背景颜色通过 config 方法设置为紫色调,增强了界面的视觉效果。

文件路径输入与验证

工具允许用户通过输入框指定 HTML 文件的路径,并在执行转换前验证路径的有效性。以下是文件路径输入与验证的代码片段及解析:

fileText = Entry(root, bg="white", fg='#7a1da3',
                 highlightbackground=color, highlightcolor=color,
                 highlightthickness=3, bd=0, font=textHighlightFont)
fileText.pack(fill=X)

def markdown():
    filename = fileText.get()
    filepath = os.path.join(cwd + '\\AlHtmlToMarkdown', filename)
    if os.path.exists(filepath):
        extension = os.path.splitext(filepath)[1]
        if extension.lower() == ".html":
            # 执行转换操作
        else:
            text.insert(1.0, 'Invalid document, please provide .html extension files')
    else:
        text.insert(1.0, 'Invalid file path')

在上述代码中,Entry 是一个输入框组件,用户可以在其中输入 HTML 文件的路径。markdown 函数用于处理转换操作,首先验证文件路径是否存在,然后检查文件扩展名是否为 .html。如果路径无效或文件类型不正确,工具会通过 Text 组件向用户显示错误信息。

HTML 到 Markdown 格式转换

工具的核心功能是将 HTML 文件转换为 Markdown 文件。以下是格式转换的代码片段及解析:

import markdownify

def markdown():
    filename = fileText.get()
    filepath = os.path.join(cwd + '\\AlHtmlToMarkdown', filename)
    if os.path.exists(filepath):
        extension = os.path.splitext(filepath)[1]
        if extension.lower() == ".html":
            htmlFile = open(filepath, "r")
            html = htmlFile.read()
            htmlFile.close()
            markDown = markdownify.markdownify(html, heading_style="ATX")
            markdownFileName = filename.replace(extension, '.md')
            markdownFilePath = os.path.join(cwd + '\\AlHtmlToMarkdown\\Markdown', markdownFileName)
            markdownFile = open(markdownFilePath, "w")
            markdownFile.writelines(markDown)
            markdownFile.close()
            text.delete(1.0, END)
            text.insert(1.0, markdownFileName + ' has been saved successfully in Markdown folder')

在上述代码中,markdownify.markdownify 方法用于将 HTML 内容转换为 Markdown 格式。工具首先读取用户指定的 HTML 文件内容,然后调用 markdownify 函数进行转换,并将结果保存为一个新的 Markdown 文件。转换完成后,工具会在界面中显示成功消息。

窗口操作与用户体验优化

为了提升用户体验,工具提供了窗口最小化、关闭等操作,并通过自定义标题栏实现了无边框窗口的效果。以下是窗口操作的代码片段及解析:

def hideScreen():
    root.overrideredirect(0)
    root.iconify()

def showScreen(event):
    root.deiconify()
    root.overrideredirect(1)

closeButton = Button(titleBar, text="x", bg='#141414', fg="#909090",
                     borderwidth=0, command=root.destroy,
                     font=appHighlightFont)
closeButton.grid(row=0, column=3, sticky="nsew")

minimizeButton = Button(titleBar, text="-", bg='#141414', fg="#909090",
                        borderwidth=0, command=hideScreen,
                        font=appHighlightFont)
minimizeButton.grid(row=0, column=2, sticky="nsew")

在上述代码中,overrideredirect 方法用于隐藏窗口的默认标题栏,实现自定义标题栏的效果。iconify 方法用于最小化窗口,deiconify 方法用于恢复窗口。通过自定义的关闭按钮和最小化按钮,用户可以方便地操作窗口。

方法扩展

使用python自动化将markdown文件转成html

完整代码

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# 使用方法 python markdown_convert.py filename
import sys
import markdown
import codecs
import base64 
import re
css = '''
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />  
<style type="text/css">  
body {  
    font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Helvetica, Arial, sans-serif;  
    line-height: 1.6;  
    color: #333;  
    max-width: 800px;  
    margin: 0 auto;  
    padding: 20px;  
}  
h1, h2, h3, h4, h5, h6 {  
    margin-top: 1.2em;  
    margin-bottom: 0.6em;  
    font-weight: 600;  
}  
h1 { font-size: 2em; border-bottom: 1px solid #eee; padding-bottom: 0.3em; }  
h2 { font-size: 1.5em; border-bottom: 1px solid #eee; padding-bottom: 0.2em; }  
h3 { font-size: 1.25em; }  
h4 { font-size: 1em; }  
h5 { font-size: 0.875em; }  
h6 { font-size: 0.85em; color: #777; }  
p { margin: 0 0 1em; }  
a { color: #0366d6; text-decoration: none; }  
a:hover { text-decoration: underline; }  
code {  
    font-family: SFMono-Regular, Consolas, "Liberation Mono", Menlo, monospace;  
    background-color: #f6f8fa;  
    padding: 0.2em 0.4em;  
    border-radius: 3px;  
    font-size: 85%;  
}  
pre {  
    background-color: #f6f8fa;  
    padding: 16px;  
    overflow: auto;  
    border-radius: 3px;  
    line-height: 1.45;  
}  
pre code {  
    padding: 0;  
    background-color: transparent;  
}  
blockquote {  
    margin: 0;  
    padding: 0 1em;  
    color: #6a737d;  
    border-left: 0.25em solid #dfe2e5;  
}  
img { max-width: 100%; }  
table {  
    border-collapse: collapse;  
    width: 100%;  
    margin-bottom: 16px;  
}  
table th, table td {  
    padding: 6px 13px;  
    border: 1px solid #dfe2e5;  
}  
table tr {  
    background-color: #fff;  
    border-top: 1px solid #c6cbd1;  
}  
table tr:nth-child(2n) {  
    background-color: #f6f8fa;  
}  
hr {  
    height: 0.25em;  
    padding: 0;  
    margin: 24px 0;  
    background-color: #e1e4e8;  
    border: 0;  
}  
</style>  
'''
def embed_images(html_content):  
    def replace_with_base64(match):  
        img_path = match.group(1)  
        try:  
            with open(img_path, "rb") as img_file:  
                img_data = base64.b64encode(img_file.read()).decode("utf-8")  
                return f'src="data:image/png;base64,{img_data}"'  
        except:  
            return match.group(0)  # 失败时保持原路径  
    
    html_content = re.sub(  
        r'src=["\'](.*?\.(?:png|jpg|jpeg|gif))["\']',  
        replace_with_base64,  
        html_content  
    )  
    return html_content  
 
#sys.argv[0] 是脚本的名称(如 script.py),sys.argv[1:] 是从第二个参数开始的所有后续参数(即用户输入的参数)
def main(argv):
    name = argv[0]
    in_file = '%s.md' % (name)
    out_file = '%s.html' % (name)
 
    input_file = codecs.open(in_file, mode="r", encoding="utf-8")
    text = input_file.read()
    html = markdown.markdown(text)
    html = embed_images(html)  
    output_file = codecs.open(out_file, "w",encoding="utf-8",errors="xmlcharrefreplace")
    output_file.write(css+html)
 
if __name__ == "__main__":
   main(sys.argv[1:])

总结

本文介绍了一个基于 Python 的 HTML 到 Markdown 转换工具,它通过结合 markdownify 库的格式转换功能和 tkinter 库的图形用户界面设计,实现了从 HTML 文件到 Markdown 文件的自动化转换。该工具具有简单易用、功能实用的特点,适用于需要进行文档格式转换的各种场景。通过本文的介绍,读者可以了解到如何利用 Python 相关技术栈实现文档格式转换工具的开发,为文档处理和内容创作提供了有益的参考。

以上就是基于Python实现HTML转Markdown格式的小工具的详细内容,更多关于Python HTML转Markdown的资料请关注脚本之家其它相关文章!

相关文章

  • Python代码实现http/https代理服务器的脚本

    Python代码实现http/https代理服务器的脚本

    这篇文章主要介绍了Python代码做出http/https代理服务器,启动即可做http https透明代理使用,通过几百行代码做出http/https代理服务器代码片段,需要的朋友可以参考下
    2019-08-08
  • python序列化与数据持久化实例详解

    python序列化与数据持久化实例详解

    这篇文章主要介绍了python序列化与数据持久化,结合实例形式详细分析了Python序列化与数据持久化相关原理、实现技巧与操作注意事项,需要的朋友可以参考下
    2019-12-12
  • python基础教程之csv格式文件的写入与读取

    python基础教程之csv格式文件的写入与读取

    逗号分隔值(Comma-Separated Values,CSV,也称为字符分隔值,分隔字符也可以不是逗号),新这篇文章主要给大家介绍了关于python基础教程之csv格式文件的写入与读取的相关资料,需要的朋友可以参考下
    2022-03-03
  • SQLAlchemy的主要组件详细讲解

    SQLAlchemy的主要组件详细讲解

    SQLAlchemy是一个基于Python实现的ORM框架,能满足大多数数据库操作需求,同时支持多种数据库引擎(SQLite,MySQL,Postgresql,Oracle等),这篇文章主要介绍了SQLAlchemy的主要组件有哪些,本文给大家介绍的非常详细,对大家的学习具有一定的参考借鉴价值,需要的朋友可以参考
    2023-08-08
  • python中子类与父类的关系基础知识点

    python中子类与父类的关系基础知识点

    在本篇文章里小编给大家整理的是一篇关于python中子类与父类的关系基础知识点内容,对此有兴趣的朋友们可以学习下。
    2021-02-02
  • 设计模式中的原型模式在Python程序中的应用示例

    设计模式中的原型模式在Python程序中的应用示例

    这篇文章主要介绍了设计模式中的原型模式在Python程序中的应用示例,文中主要强调了对浅拷贝和深拷贝在对象复制时的使用,需要的朋友可以参考下
    2016-03-03
  • Python3+Appium实现多台移动设备操作的方法

    Python3+Appium实现多台移动设备操作的方法

    这篇文章主要介绍了Python3+Appium实现多台移动设备操作的方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2019-07-07
  • Flask实现定制日志并输出到文件

    Flask实现定制日志并输出到文件

    这篇文章主要为大家学习介绍了Flask如何实现定制日志并输出到文件,文中的示例代码简介易懂,感兴趣的小伙伴快跟随小编一起学习一下吧
    2023-07-07
  • 一文详解Python三引号(“““)的五个神奇用法

    一文详解Python三引号(“““)的五个神奇用法

    今天我们来聊一聊 Python 中的一个神奇字符——三引号("""),三引号"""不仅仅是用来定义多行字符串的简单工具,它还隐藏着许多令人惊叹的用途,感兴趣的小伙伴跟着小编一起来看看吧
    2025-04-04
  • Python循环语句中else的用法总结

    Python循环语句中else的用法总结

    这篇文章给大家整理了关于Python中循环语句中else的用法,包括常规的 if else 用法、if else 快捷用法、与 for 关键字一起用、与 while 关键字一起用以及与 try except 一起用的用法总结,有需要的朋友们可以参考借鉴。
    2016-09-09

最新评论