python

关注公众号 jb51net

关闭
首页 > 脚本专栏 > python > Python HTML转Markdown

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

作者: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的资料请关注脚本之家其它相关文章!

您可能感兴趣的文章:
阅读全文