Python使用FastMCP實現(xiàn)Word文檔與JSON數(shù)據(jù)互轉(zhuǎn)
一、項目背景
本文分享一個基于 FastMCP 框架實現(xiàn)的文檔處理服務(wù),可實現(xiàn) Word 文檔(.docx)與 JSON 數(shù)據(jù)格式的雙向轉(zhuǎn)換。通過此服務(wù),開發(fā)者可以輕松實現(xiàn)文檔內(nèi)容提取、結(jié)構(gòu)化數(shù)據(jù)填充、樣式模板復(fù)用等功能,適用于自動化報告生成、數(shù)據(jù)導(dǎo)入導(dǎo)出等場景。
二、核心代碼解析
1. 服務(wù)端實現(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'
# 啟動 MCP 服務(wù)
if __name__ == "__main__":
mcp.run(transport="streamable-http", host="127.0.0.1", port=9000)
關(guān)鍵組件說明:
- FastMCP:基于 MCP 協(xié)議的服務(wù)框架,提供工具注冊與調(diào)用能力
- wan_neng_copy_word 系列模塊:實現(xiàn) Word 文檔解析與生成的核心邏輯
- gen_all_styles:樣式模板生成工具
- 雙向轉(zhuǎn)換邏輯:
word_to_json:提取文檔內(nèi)容結(jié)構(gòu)并序列化為 JSONjson_to_word:應(yīng)用模板樣式生成新文檔
2. 客戶端測試代碼
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)建客戶端實例
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())
三、運行環(huán)境要求
- Python 3.8+ 環(huán)境
- 依賴庫安裝:
pip install fastmcp python-docx
- 文件依賴:
demo_template.docx(樣式模板)1.docx(輸入文檔)1.json(結(jié)構(gòu)化數(shù)據(jù))
四、功能演示流程
啟動服務(wù):
python my_server.py
執(zhí)行客戶端測試:
python client_test.py
- 輸出結(jié)果:
- 生成
cloned_example.docx文檔 - 驗證文檔內(nèi)容與原始模板樣式的一致性
- 生成
五、應(yīng)用場景
- 自動化報告生成:通過 API 動態(tài)填充數(shù)據(jù)到預(yù)設(shè)模板
- 文檔結(jié)構(gòu)分析:提取 Word 內(nèi)容進行 NLP 處理
- 跨格式轉(zhuǎn)換:作為其他格式(如 Markdown、HTML)轉(zhuǎn)換的中間層
- 樣式統(tǒng)一管理:基于模板批量生成標(biāo)準(zhǔn)化文檔
六、注意事項
- 文件路徑問題:確保工作目錄包含所需模板文件
- 異常處理增強建議:
# 可擴展的異常處理示例
try:
# 文件操作代碼
except FileNotFoundError as e:
return {"error": f"Missing file: {str(e)}"}
except json.JSONDecodeError:
return {"error": "Invalid JSON input"}
- 性能優(yōu)化方向:
- 添加緩存機制復(fù)用樣式模板
- 支持異步文件讀寫
- 實現(xià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實現(xiàn)多格式轉(zhuǎn)換 - 添加 PDF 導(dǎo)出功能
API 接口增強:
- 添加文件上傳下載接口
- 實現(xiàn)任務(wù)隊列異步處理
該實現(xiàn)展示了如何通過 MCP 協(xié)議構(gòu)建文檔處理服務(wù),開發(fā)者可根據(jù)實際需求擴展更多文檔操作功能。完整項目代碼需注意分離服務(wù)端/客戶端模塊,并完善錯誤處理機制。
以上就是Python使用FastMCP實現(xiàn)Word文檔與JSON數(shù)據(jù)互轉(zhuǎn)的詳細內(nèi)容,更多關(guān)于Python Word與JSON互轉(zhuǎn)的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Python Shiny庫創(chuàng)建交互式Web應(yīng)用及高級功能案例
Shiny是一個基于Python的交互式Web應(yīng)用框架,專注于簡化Web應(yīng)用的開發(fā)流程,本文將深入探討Shiny庫的基本用法、高級功能以及實際應(yīng)用案例,以幫助開發(fā)者充分發(fā)揮Shiny在Web應(yīng)用開發(fā)中的優(yōu)勢2023-12-12
python實現(xiàn)xml轉(zhuǎn)json文件的示例代碼
這篇文章主要介紹了python實現(xiàn)xml轉(zhuǎn)json文件的示例代碼,幫助大家更好的理解和使用python,感興趣的朋友可以了解下2020-12-12
淺析Python中常見數(shù)據(jù)脫敏技術(shù)應(yīng)用與對比
數(shù)據(jù)脫敏通過對敏感數(shù)據(jù)進行轉(zhuǎn)換,確保其在保護隱私的同時仍能用于開發(fā),本文為大家整理了一些常見的數(shù)據(jù)脫敏技術(shù),感興趣的小伙伴可以了解下2025-02-02
Python 如何定義匿名或內(nèi)聯(lián)函數(shù)
這篇文章主要介紹了Python 如何定義匿名或內(nèi)聯(lián)函數(shù),文中講解非常細致,代碼幫助大家更好的理解和學(xué)習(xí),感興趣的朋友可以了解下2020-08-08

