最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Python將Markdown文件轉(zhuǎn)換為Word(docx)完整教學(xué)

 更新時間:2025年12月26日 14:47:49   作者:weixin_46244623  
在實際開發(fā)中,經(jīng)常會遇到將 Markdown 文檔轉(zhuǎn)換為 Word(.docx)的需求,下面小編就和大家詳細(xì)介紹一下Python將Markdown文件轉(zhuǎn)換為Word的完整步驟吧

在實際開發(fā)中,經(jīng)常會遇到將 Markdown 文檔轉(zhuǎn)換為 Word(.docx)的需求,例如:

  • 技術(shù)文檔從 Markdown 遷移到 Word
  • 自動生成可下載的 Word 報告
  • 與 Dify、FastAPI 等系統(tǒng)結(jié)合做文檔導(dǎo)出

本文基于 python-docx + markdown + BeautifulSoup,實現(xiàn)一個不依賴接口、直接讀取 Markdown 文件并生成 Word 文件的完整方案,支持常見 Markdown 語法。

一、實現(xiàn)思路說明

整體轉(zhuǎn)換流程如下:

  • 使用 markdown 庫將 Markdown 文本轉(zhuǎn)換為 HTML
  • 使用 BeautifulSoup 解析 HTML 結(jié)構(gòu)
  • 遍歷 HTML 節(jié)點(diǎn),映射為 Word 中的對應(yīng)元素
  • 使用 python-docx 生成并保存 .docx 文件

支持的 Markdown 元素包括:

  • 標(biāo)題(h1–h6)
  • 段落
  • 無序 / 有序列表
  • 代碼塊
  • 行內(nèi)代碼、加粗、斜體
  • 表格

二、依賴安裝

pip install python-docx markdown beautifulsoup4

三、完整代碼實現(xiàn)

from docx import Document
from docx.shared import Pt
from bs4 import BeautifulSoup
import markdown
import uuid
import os

FILE_DIR = "static"
os.makedirs(FILE_DIR, exist_ok=True)


def md_to_word(md_text: str) -> str:
    """
    將 Markdown 文本轉(zhuǎn)換為 Word,返回生成的文件名
    """
    html = markdown.markdown(
        md_text,
        extensions=["extra", "tables", "fenced_code"]
    )

    soup = BeautifulSoup(html, "html.parser")
    doc = Document()

    for element in soup.contents:
        handle_element(doc, element)

    filename = f"{uuid.uuid4().hex}.docx"
    file_path = os.path.join(FILE_DIR, filename)
    doc.save(file_path)

    return filename


def handle_element(doc, el):
    if not hasattr(el, "name") or el.name is None:
        return

    # 標(biāo)題
    if el.name in ["h1", "h2", "h3", "h4", "h5", "h6"]:
        doc.add_heading(el.get_text(), level=int(el.name[1]))
        return

    # 段落
    if el.name == "p":
        p = doc.add_paragraph()
        add_inline_text(p, el)
        return

    # 無序列表
    if el.name == "ul":
        for li in el.find_all("li", recursive=False):
            p = doc.add_paragraph(style="List Bullet")
            add_inline_text(p, li)
        return

    # 有序列表
    if el.name == "ol":
        for li in el.find_all("li", recursive=False):
            p = doc.add_paragraph(style="List Number")
            add_inline_text(p, li)
        return

    # 代碼塊
    if el.name == "pre":
        code_el = el.find("code")
        code = code_el.get_text() if code_el else el.get_text()
        p = doc.add_paragraph()
        run = p.add_run(code)
        run.font.name = "Courier New"
        run.font.size = Pt(10)
        return

    # 表格
    if el.name == "table":
        rows = el.find_all("tr")
        cols = rows[0].find_all(["th", "td"])
        table = doc.add_table(rows=len(rows), cols=len(cols))
        table.style = "Table Grid"

        for r, row in enumerate(rows):
            for c, cell in enumerate(row.find_all(["th", "td"])):
                paragraph = table.rows[r].cells[c].paragraphs[0]
                run = paragraph.add_run(cell.get_text())
                if cell.name == "th":
                    run.bold = True


def add_inline_text(paragraph, el):
    """
    處理行內(nèi)樣式:加粗、斜體、行內(nèi)代碼
    """
    for node in el.contents:
        if isinstance(node, str):
            paragraph.add_run(node)
        else:
            run = paragraph.add_run(node.get_text())
            if node.name == "strong":
                run.bold = True
            elif node.name == "em":
                run.italic = True
            elif node.name == "code":
                run.font.name = "Courier New"
                run.font.size = Pt(10)


def md_to_word_from_file(md_file_path: str) -> str:
    """
    從 Markdown 文件生成 Word
    """
    with open(md_file_path, "r", encoding="utf-8") as f:
        md_text = f.read()

    return md_to_word(md_text)


if __name__ == "__main__":
    md_path = "jd.md"   # Markdown 文件路徑
    filename = md_to_word_from_file(md_path)
    print("生成的 Word 文件:", filename)

四、使用說明

將 Markdown 文件(如 jd.md)放到當(dāng)前目錄

運(yùn)行腳本:

python md_to_word.py

程序會在 static/ 目錄下生成一個 .docx 文件,文件名為 UUID

五、適用場景

FastAPI / Flask 文檔導(dǎo)出

Dify 工作流中生成 Word 報告

Markdown 文檔批量轉(zhuǎn) Word

內(nèi)部系統(tǒng)自動生成可編輯文檔

六、可優(yōu)化方向

增加圖片(img)支持

支持代碼高亮樣式

表格列寬自適應(yīng)

自定義標(biāo)題樣式、字體、行距

與 FastAPI 接口結(jié)合返回下載地址

七、總結(jié)

本文實現(xiàn)了一個輕量、可控、易擴(kuò)展的 Markdown 轉(zhuǎn) Word 方案,不依賴外部接口,適合后端服務(wù)或本地腳本使用。

對于需要文檔導(dǎo)出、報告生成的場景,這種方式在穩(wěn)定性和可維護(hù)性上都具有明顯優(yōu)勢。

如果你后續(xù)需要 FastAPI 接口版、Dify 工作流集成版 或 樣式增強(qiáng)版,可以在此基礎(chǔ)上直接擴(kuò)展。

到此這篇關(guān)于Python將Markdown文件轉(zhuǎn)換為Word(docx)完整教學(xué)的文章就介紹到這了,更多相關(guān)Python Markdown轉(zhuǎn)Word內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論

康平县| 乌兰县| 南宫市| 牙克石市| 穆棱市| 巴楚县| 古丈县| 勃利县| 麟游县| 邻水| 黄浦区| 特克斯县| 浦县| 白沙| 灵璧县| 鄂伦春自治旗| 濉溪县| 旬阳县| 黄石市| 商河县| 孝昌县| 鱼台县| 桓仁| 自治县| 郴州市| 平远县| 双桥区| 亳州市| 武平县| 哈巴河县| 长丰县| 怀来县| 乐东| 民勤县| 武城县| 长子县| 百色市| 辽阳县| 绵竹市| 保定市| 盱眙县|