当前位置: 代码网 > it编程>前端脚本>Python > 基于Python实现HTML转Markdown格式的小工具

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

2025年07月10日 Python 我要评论
引言在现代文档处理和内容创作中,html 和 markdown 是两种广泛使用的格式。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的资料请关注代码网其它相关文章!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com