欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python使用FastMCP實(shí)現(xiàn)Word文檔與JSON數(shù)據(jù)互轉(zhuǎn)

 更新時(shí)間:2025年06月16日 09:01:48   作者:東方佑  
這篇文章主要介紹了基于FastMCP框架實(shí)現(xiàn)的文檔處理服務(wù),可實(shí)現(xiàn)?Word?文檔(.docx)與?JSON?數(shù)據(jù)格式的雙向轉(zhuǎn)換,通過此服務(wù),開發(fā)者可以輕松實(shí)現(xiàn)文檔內(nèi)容提取、結(jié)構(gòu)化數(shù)據(jù)填充、樣式模板復(fù)用等功能,適用于自動(dòng)化報(bào)告生成、數(shù)據(jù)導(dǎo)入導(dǎo)出等場(chǎng)景,需要的朋友可以參考下

一、項(xiàng)目背景

本文分享一個(gè)基于 FastMCP 框架實(shí)現(xiàn)的文檔處理服務(wù),可實(shí)現(xiàn) Word 文檔(.docx)與 JSON 數(shù)據(jù)格式的雙向轉(zhuǎn)換。通過此服務(wù),開發(fā)者可以輕松實(shí)現(xiàn)文檔內(nèi)容提取、結(jié)構(gòu)化數(shù)據(jù)填充、樣式模板復(fù)用等功能,適用于自動(dòng)化報(bào)告生成、數(shù)據(jù)導(dǎo)入導(dǎo)出等場(chǎng)景。

二、核心代碼解析

1. 服務(wù)端實(shí)現(xiàn)(my_server.py)

import json
from fastmcp import FastMCP
from wan_neng_copy_word import clone_document as word_to_dict
from wan_neng_copy_word_pro import clone_document
from wan_neng_copy_word import clone_document as get_para_style
from gen_all_styles import gen_all_styles

mcp = FastMCP(name="MyServer")

# 基礎(chǔ)問候工具
@mcp.tool
def greet(name: str) -> str:
    """Greet a user by name."""
    return f"Hello, {name}!"

# Word 轉(zhuǎn) JSON 工具
@mcp.tool
def word_to_json(word_path: str) -> str:
    """Convert a word document to json."""
    body_s, body_p = word_to_dict(word_path)
    return json.dumps(body_p)

# JSON 轉(zhuǎn) Word 工具
@mcp.tool
def json_to_word(word_path: str, json_data: str) -> str:
    """Convert a json to word document."""
    try:
        body_ws, _ = get_para_style('demo_template.docx')
    except:
        gen_all_styles()
        body_ws, _ = get_para_style('demo_template.docx')

    body_s, _ = get_para_style(word_path)
    clone_document(body_s, json.loads(json_data), body_ws, 'cloned_example.docx')
    return 'cloned_example.docx'

# 啟動(dòng) MCP 服務(wù)
if __name__ == "__main__":
    mcp.run(transport="streamable-http", host="127.0.0.1", port=9000)

關(guān)鍵組件說明:

  • FastMCP:基于 MCP 協(xié)議的服務(wù)框架,提供工具注冊(cè)與調(diào)用能力
  • wan_neng_copy_word 系列模塊:實(shí)現(xiàn) Word 文檔解析與生成的核心邏輯
  • gen_all_styles:樣式模板生成工具
  • 雙向轉(zhuǎn)換邏輯
    • word_to_json:提取文檔內(nèi)容結(jié)構(gòu)并序列化為 JSON
    • json_to_word:應(yīng)用模板樣式生成新文檔

2. 客戶端測(cè)試代碼

import asyncio
from fastmcp import Client

# MCP 服務(wù)配置
config = {
    "mcpServers": {
        "document-service": {
            "url": "http://127.0.0.1:9000/mcp",
            "transport": "streamable-http"
        }
    }
}

# 創(chuàng)建客戶端實(shí)例
client = Client(config)

async def main():
    async with client:
        # 讀取 JSON 數(shù)據(jù)
        with open("1.json", "r", encoding="utf-8") as f:
            body_p = f.read()
        
        # 調(diào)用 JSON 轉(zhuǎn) Word 工具
        result = await client.call_tool(
            "json_to_word", 
            {"word_path": "1.docx", "json_data": body_p}
        )
        print(f"生成文檔路徑: {result}")

if __name__ == "__main__":
    asyncio.run(main())

三、運(yùn)行環(huán)境要求

  • Python 3.8+ 環(huán)境
  • 依賴庫安裝:
pip install fastmcp python-docx
  • 文件依賴:
    • demo_template.docx(樣式模板)
    • 1.docx(輸入文檔)
    • 1.json(結(jié)構(gòu)化數(shù)據(jù))

四、功能演示流程

啟動(dòng)服務(wù):

python my_server.py

執(zhí)行客戶端測(cè)試:

python client_test.py
  • 輸出結(jié)果:
    • 生成 cloned_example.docx 文檔
    • 驗(yàn)證文檔內(nèi)容與原始模板樣式的一致性

五、應(yīng)用場(chǎng)景

  • 自動(dòng)化報(bào)告生成:通過 API 動(dòng)態(tài)填充數(shù)據(jù)到預(yù)設(shè)模板
  • 文檔結(jié)構(gòu)分析:提取 Word 內(nèi)容進(jìn)行 NLP 處理
  • 跨格式轉(zhuǎn)換:作為其他格式(如 Markdown、HTML)轉(zhuǎn)換的中間層
  • 樣式統(tǒng)一管理:基于模板批量生成標(biāo)準(zhǔn)化文檔

六、注意事項(xiàng)

  • 文件路徑問題:確保工作目錄包含所需模板文件
  • 異常處理增強(qiáng)建議
# 可擴(kuò)展的異常處理示例
try:
    # 文件操作代碼
except FileNotFoundError as e:
    return {"error": f"Missing file: {str(e)}"}
except json.JSONDecodeError:
    return {"error": "Invalid JSON input"}
  • 性能優(yōu)化方向
    • 添加緩存機(jī)制復(fù)用樣式模板
    • 支持異步文件讀寫
    • 實(shí)現(xiàn)流式傳輸處理大文件

七、擴(kuò)展建議

添加文件校驗(yàn)?zāi)K:

def validate_word_file(path):
    if not os.path.exists(path):
        raise ValueError("Template file not found")
    if not path.endswith('.docx'):
        raise ValueError("Invalid file format")

支持更多格式轉(zhuǎn)換:

  • 集成 pandoc 實(shí)現(xiàn)多格式轉(zhuǎn)換
  • 添加 PDF 導(dǎo)出功能

API 接口增強(qiáng):

  • 添加文件上傳下載接口
  • 實(shí)現(xiàn)任務(wù)隊(duì)列異步處理

該實(shí)現(xiàn)展示了如何通過 MCP 協(xié)議構(gòu)建文檔處理服務(wù),開發(fā)者可根據(jù)實(shí)際需求擴(kuò)展更多文檔操作功能。完整項(xiàng)目代碼需注意分離服務(wù)端/客戶端模塊,并完善錯(cuò)誤處理機(jī)制。

以上就是Python使用FastMCP實(shí)現(xiàn)Word文檔與JSON數(shù)據(jù)互轉(zhuǎn)的詳細(xì)內(nèi)容,更多關(guān)于Python Word與JSON互轉(zhuǎn)的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

最新評(píng)論