Python使用FastMCP實(shí)現(xiàn)Word文檔與JSON數(shù)據(jù)互轉(zhuǎn)
一、項(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)并序列化為 JSONjson_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)文章
Python Shiny庫創(chuàng)建交互式Web應(yīng)用及高級(jí)功能案例
Shiny是一個(gè)基于Python的交互式Web應(yīng)用框架,專注于簡(jiǎn)化Web應(yīng)用的開發(fā)流程,本文將深入探討Shiny庫的基本用法、高級(jí)功能以及實(shí)際應(yīng)用案例,以幫助開發(fā)者充分發(fā)揮Shiny在Web應(yīng)用開發(fā)中的優(yōu)勢(shì)2023-12-12
python實(shí)現(xiàn)xml轉(zhuǎn)json文件的示例代碼
這篇文章主要介紹了python實(shí)現(xiàn)xml轉(zhuǎn)json文件的示例代碼,幫助大家更好的理解和使用python,感興趣的朋友可以了解下2020-12-12
淺析Python中常見數(shù)據(jù)脫敏技術(shù)應(yīng)用與對(duì)比
數(shù)據(jù)脫敏通過對(duì)敏感數(shù)據(jù)進(jìn)行轉(zhuǎn)換,確保其在保護(hù)隱私的同時(shí)仍能用于開發(fā),本文為大家整理了一些常見的數(shù)據(jù)脫敏技術(shù),感興趣的小伙伴可以了解下2025-02-02
Python 如何定義匿名或內(nèi)聯(lián)函數(shù)
這篇文章主要介紹了Python 如何定義匿名或內(nèi)聯(lián)函數(shù),文中講解非常細(xì)致,代碼幫助大家更好的理解和學(xué)習(xí),感興趣的朋友可以了解下2020-08-08
Python3.x爬蟲下載網(wǎng)頁圖片的實(shí)例講解
今天小編就為大家分享一篇Python3.x爬蟲下載網(wǎng)頁圖片的實(shí)例講解,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2018-05-05
Django使用中間鍵實(shí)現(xiàn)csrf認(rèn)證詳解
這篇文章主要介紹了Django使用中間鍵實(shí)現(xiàn)csrf認(rèn)證詳解,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-07-07

