主要功能是按照JSON文件(Sort.json)中指定的順序合并多個Word文檔(.docx),并清除文檔中的所有超鏈接。最終輸出合并后的文檔名為"sorted_按章節順序.docx"。
主要分為幾個部分:
初始化配置
- 定義超鏈接清除函數(處理段落+表格)
- 獲取當前工作目錄
讀取排序規則
- 解析Sort.json文件
- 構建完整文件路徑列表
文件驗證
- 檢查JSON中所有文件是否存在
- 輸出缺失文件警告
主流程:讀取JSON,驗證文件,合并文檔
環境配置步驟:
安裝好 Python 和成功配置相應的環境變量,我的 Python 版本為 3.8.2
需要安裝 win32com、docx、docxcompose,分別輸入以下代碼安裝
pip install pypiwin32
pip install python-docx
pip install docxcompose
💡 提示:安裝后可通過 python -c "import win32com; print('成功')" 驗證
代碼簡略版:
!/usr/bin/python3.6
# -*- coding: utf-8 -*-
"""
@Time :24-12 10:07
@Software: PyCharm
@Project :Merge files001
"""
import os
import json
from docx import Document
from docxcompose.composer import Composer# 清除文檔中的所有超鏈接
def remove_hyperlinks(doc):for para in doc.paragraphs:for run in para.runs:# 通過run的XML屬性查看是否為超鏈接if 'hyperlink' in run._r.xml:run._r.getparent().remove(run._r) for table in doc.tables:for row in table.rows:for cell in row.cells:for para in cell.paragraphs:for run in para.runs:if 'hyperlink' in run._r.xml:run._r.getparent().remove(run._r)
# 獲取當前工作目錄( cwd )
cwd = os.getcwd()
# 讀取JSON文件并獲取排序信息
def get_order_from_json(json_path):# 讀取 JSON 文件,獲取文件列表with open(json_path, 'r', encoding='utf-8') as f:data = json.load(f)return [os.path.join(cwd, 'Word_Test', file_name) for file_name in data['file_order']]
# 調用函數讀取排序信息
json_path = 'Sort.json' #JSON文件路徑
ordered_files = get_order_from_json(json_path)# 使用排序后的文件列表進行合并
def combine_all_docx_ordered(filename_master, files_list_ordered):# 確保文件列表不為空if not files_list_ordered:print("沒有文檔可供合并。")returntry:master = Document(filename_master) remove_hyperlinks(master) except Exception as e:print(f"無法打開主文檔{filename_master}:{e}")return# 在循環之前添加一個分頁符,合并后的文檔從第二頁開始。master.add_page_break() composer = Composer(master)# 如果文件列表中只有一個文件,即主文檔自身,直接保存即可if len(files_list_ordered) == 1:print("只有一個文檔,無需合并。")master.save("single_doc.docx")returnfor doc_temp_path in files_list_ordered[1:]: try:doc_temp = Document(doc_temp_path) remove_hyperlinks(doc_temp) except Exception as e:print(f"無法打開文檔 {doc_temp_path}:{e}")continuedoc_temp.add_page_break() composer.append(doc_temp) # 保存合并后的文檔try:composer.save("sorted_按章節順序.docx")print("合并后的文檔已保存。")except Exception as e:print(f"保存合并文檔時出錯: {e}")# 驗證JSON中的文件是否存在
def verify_files_existence(files_paths):existing_files = []missing_files = []for file_path in files_paths:if os.path.exists(file_path):existing_files.append(file_path)else:missing_files.append(file_path)return existing_files, missing_files
# 驗證文件并處理不存在的文件
existing_files, missing_files = verify_files_existence(ordered_files)if missing_files:print("以下文件在JSON中指定但未找到:")for missing_file in missing_files:print(missing_file)
else:# 合并文檔# 調用新的函數進行合并combine_all_docx_ordered(ordered_files[0], ordered_files)print("————按JSON排序合并完成————")
創建 Sort.json 文件,其中按自定義順序存儲需合并的 Word 文檔名稱。
運行腳本后,程序將按 JSON 定義的順序自動合并文檔。