Hongmu Notes
Home Language Notes Python converts Markdown to HTML – Code Backup
Language Notes python

Python converts Markdown to HTML – Code Backup

Python converts Markdown to HTML – Code Backup

It took an entire day to figure this thing out – I really ran into some issues with Markdown.

Back up your code here to prevent loss!

I have packaged it as software; please collect it in person if needed:

https://www.4s5.cn/archives/1310.html

 隐藏内容:付费阅读
import os
import re
import logging
import markdown

print("软件作者QQ:1810216796\n站长技术交流群:958972323,欢迎大家加入交流!")

# 创建md和html目录
if not os.path.exists('md'):
    os.makedirs('md')
if not os.path.exists('html'):
    os.makedirs('html')

# 设置日志记录
logging.basicConfig(filename='markdown_conversion.log', level=logging.DEBUG,
                    format='%(asctime)s - %(levelname)s - %(message)s', encoding='utf-8')

# 获取用户输入的文件后缀名
md_file_extension = input('请输入存放Markdown文件的后缀名(如.md):').strip()
if not md_file_extension.startswith('.'):
    md_file_extension = '.' + md_file_extension

# 获取用户输入的HTML文件后缀名
html_file_extension = input('请输入要生成的HTML文件的后缀名(如.html):').strip()
if not html_file_extension.startswith('.'):
    html_file_extension = '.' + html_file_extension

# 检查并修复Markdown语法和格式

def check_and_fix_md(md_text, file_name):
    try:
        html_text = markdown.markdown(
            md_text, extensions=['codehilite', 'fenced_code', 'tables'])
        logging.info(f'成功将"{file_name}"转换为HTML')
    except Exception as e:
        error_msg = str(e)
        logging.error(f'转换Markdown文件"{file_name}"时出错: {error_msg}')
        if error_msg.startswith('unexpected indent'):
            md_text = re.sub(r'\n\s+', '\n', md_text)
        elif error_msg.startswith('expected block end'):
            md_text = re.sub(r'\n\n+', '\n\n', md_text)
        html_text = markdown.markdown(
            md_text, extensions=['codehilite', 'fenced_code', 'tables'])
        logging.info(f'成功将"{file_name}"转换为HTML')

    return html_text

# 遍历md目录下的Markdown文件,将其转换为HTML代码并保存到html目录中
for file_name in os.listdir('md'):
    if file_name.endswith(md_file_extension):
        # 读取Markdown文件
        with open(os.path.join('md', file_name), 'r', encoding='utf-8') as f:
            md_text = f.read()
        # 检查并修复Markdown语法和格式
        html_text = check_and_fix_md(md_text, file_name)
        # 保存为HTML文件
        html_file_name = os.path.splitext(file_name)[0] + html_file_extension
        with open(os.path.join('html', html_file_name), 'w', encoding='utf-8') as f:
            f.write(html_text)
        logging.info(f'成功将"{file_name}"转换为"{html_file_name}"')
        print(f'成功将"{file_name}"转换为"{html_file_name}"')
    else:
        logging.warning(f'文件"{file_name}"不是Markdown文件,已跳过')
        print(f'文件"{file_name}"不是Markdown文件,已跳过')

微信赞赏

WeChat

支付宝赞赏

Alipay

✍️ Author: Hong Mu

webmaster · Thanks for reading, stay tuned for more exciting content

Author homepage View home page →

Related articles

Import " requests" could not be resolved from source

Import " requests" could not be resolved from source Language Notes python

This error occurred when using Pylance, a Python language server. Among them, " Import " requests" could not be resolved from source" This error message indicates that the requests module is referenced in your code, but Pylance cannot find the location of the module from the source. The possible reason is that you don't have an …
👁 1771
Reinstall Python and requests libraries

Reinstall Python and requests libraries Language Notes python

If you meet " Import " requests" could not be resolved from source" You can try reinstalling Python and requests libraries. First, you need to uninstall the current Python and requests libraries. On Windows systems, you can use the command prompt …
👁 439
WARNING: Skipping requests as it is not installed.

WARNING: Skipping requests as it is not installed. Language Notes python

This error message indicates that your Python environment lacks the requests library, and this library is called in your code, so Python cannot execute your code normally. The solution to this problem is to install the requests library. You can use the pip command on the command line to install: pip install requests If you are using Python3, you can use the pip3 command …
👁 2100
Python reported an error. What is the reason? AttributeError: partially initialized module ' openai'  has no attribute ' Completion' (most likely due to a circular import)

Python reported an error. What is the reason? AttributeError: partially initialized module ' openai' has no attribute ' Completion' (most likely due to a circular import) Language Notes python

This error prompt indicates that there is a problem when importing the openai module and the specific Completion attribute, which is probably caused by circular import. The reason for this error may be that two or more modules in your code are imported from each other, forming a circular dependency. For example, module A imports module B, and module B imports module A.. Cyclic import will cause the module not to initialize correctly when loading, thus …
👁 656
How does python package and run on Windows?

How does python package and run on Windows? Language Notes python

The most common way to package and run Python programs on Windows is to use PyInstaller. PyInstaller is a free and cross-platform Python application packaging tool, which can package Python code and its dependent libraries into an independent executable file, making it possible to run Python programs on systems without Python interpreters installed. The following is to make …
👁 300
What programming software is good for python development?

What programming software is good for python development? Language Notes python

There are many programming softwares developed by Python. The following are some commonly used Python integrated development environments (IDE) and editors: PyCharmPyCharm is an integrated development environment developed by JetBrains, which is specially designed for Python developers. PyCharm is powerful and provides a series of advanced functions such as code completion, debugging, version control, code refactoring, etc., which can help developers improve their work …
👁 175

Recommended reading

Responsive interior decoration and renovation website template – 0883

Responsive interior decoration and renovation website template – 0883 Practical Collection Yiyou template

This EyouCMS responsive template is ideal for the decoration, interior design, renovation, and home improvement industries. Its modern and professional design style enables effective presentation of renovation design projects, construction techniques, material showcases, and service workflows. It helps renovation and decoration companies attract homeowners online and secure new projects. Template Display | Installation Instructions | Website Backend: /login.php | Username: admin | Password: admin | Related Articles: Summary of Common Installation Issues for EyouCMS...
👁 36
Marketing-oriented threaded screw electroplating mechanical components website template 0088

Marketing-oriented threaded screw electroplating mechanical components website template 0088 Practical Collection Yiyou template

An eYouCMS website template designed for enterprises specializing in marketing threaded screws and electroplated mechanical components. Its professional and precise design is ideal for showcasing fastener products, electroplating processes, and mechanical accessories. This template helps hardware manufacturing companies showcase their products online and attract industrial customers. Template Overview | Installation Instructions | Website Backend: /login.php | Username: admin | Password: admin | Related Articles: Summary of Common Installation Issues for eYouCMS | eYou...
👁 36
(Adaptive Mobile Version) HTML5 Smart Device PBootCMS Website Template – Responsive AI-powered Website Source Code Download – 0492

(Adaptive Mobile Version) HTML5 Smart Device PBootCMS Website Template – Responsive AI-powered Website Source Code Download – 0492 Practical Collection pbootcms Template

A PbootCMS responsive website template designed for smart devices and AI-powered robots, compatible with both PC and WAP devices. Its futuristic design is ideal for showcasing AI products, smart hardware, and technical solutions, helping smart technology companies establish a cutting-edge online brand presence. Template Overview | Installation Instructions | Website Backend: /admin.php | Username: admin | Password: admin | Extraction Password: www.4s...
👁 47
Responsive Ceramic Grinding Disc Polishing Website Template 0884

Responsive Ceramic Grinding Disc Polishing Website Template 0884 Practical Collection Yiyou template

An eyouCMS responsive website template designed for the ceramic grinding disc and polishing industry. Its professional and precise design is ideal for showcasing grinding disc products, polishing equipment, and industrial applications. This template helps tool manufacturing enterprises showcase their products online and attract industrial customers. Template Display | Installation Instructions | Website Backend: /login.php | Username: admin | Password: admin | Related Articles: Summary of Common Installation Issues for eyouCMS | eyouCMS (...
👁 33
Responsive government agency website template 0089

Responsive government agency website template 0089 Practical Collection Yiyou template

This set of eyoucms responsive templates is suitable for government departments and units. The design style is solemn and majestic, and can display government affairs disclosure, agency functions, policies, regulations and news updates. It helps government units establish an official information release platform online. Template display Installation instructions Website backend: /login.php Account: admin Password: admin Related articles Summary of common problems in the installation of Yiyou CMS Yiyou CMS (Ey...
👁 59
(Adaptive mobile version) Responsive HR service website PBootCMS template – Enterprise management website source code download: 0493

(Adaptive mobile version) Responsive HR service website PBootCMS template – Enterprise management website source code download: 0493 Practical Collection pbootcms Template

A responsive PbootCMS website template for HR service and management consulting, compatible with both PC and WAP devices. Its professional and sophisticated design makes it ideal for HR agencies and corporate management consulting firms to showcase their services. This template helps service providers attract corporate clients online and expand their business. Template Display | Installation Instructions | Website Backend: /admin.php | Username: admin | Password: admin | Extraction Password: www.4s5....
👁 35