name: word-document-organizer version: 1.0.0 description: 智慧整理Word文件,自動格式化、生成目錄、統一樣式,支援學術/商務/極簡模板 author: Jasper.W tags: [productivity, microsoft-office, document, automation, word] tools: [bash, python]
智慧識別文件結構,自動應用標準化排版,生成專業目錄,讓文件整理一鍵完成。
當用戶提出以下請求時啟用此技能: - "整理word文件" - "格式化文件" - "生成文件目錄" - "統一文件樣式" - "排版最佳化" - "修復word格式" - "規範文件格式" - "word排版"
format: 格式化段落(行距、間距、字型統一)toc: 生成文件目錄styles: 應用標準樣式模板cleanup: 清理空段落和冗餘格式all: 執行所有操作(預設)7w4.net小蔥技能站收錄全網優質技能,值得收藏。
academic: 學術模板(宋體、層級分明,適合論文/報告)business: 商務模板(微軟雅黑、現代簡潔,適合商業文件)minimal: 極簡模板(Arial、緊湊排版,適合筆記/草稿)default: 預設模板(通用設定)#!/bin/bash
# 檢查檔案存在性
if [ ! -f "${document_path}" ]; then
echo "錯誤:檔案不存在 ${document_path}"
echo "請檢查路徑是否正確,或檔案是否被移動/刪除"
exit 1
fi
# 檢查副檔名
if [[ ! "${document_path}" =~ \.(docx|doc)$ ]]; then
echo "錯誤:僅支援 .docx 或 .doc 格式"
exit 1
fi
# 建立時間戳備份
backup_path="${document_path}.backup.$(date +%Y%m%d_%H%M%S)"
cp "${document_path}" "${backup_path}"
echo "已建立備份: ${backup_path}"
#!/bin/bash
# 檢查python-docx是否已安裝
python3 -c "import docx" 2>/dev/null || pip3 install python-docx -q
echo "依賴檢查完成"
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from docx import Document
from docx.shared import Pt, Inches, RGBColor
from docx.enum.text import WD_ALIGN_PARAGRAPH
from docx.oxml.ns import qn
import sys
import re
import os
# 獲取引數
doc_path = "${document_path}"
output_path = "${output_path}" if "${output_path}" else doc_path
template = "${style_template}"
operations = [op.strip() for op in "${operations}".split(",")] if "${operations}" else ["all"]
print(f"處理檔案: {doc_path}")
print(f"執行操作: {operations}")
print(f"使用模板: {template}")
# 載入文件
try:
doc = Document(doc_path)
except Exception as e:
print(f"無法開啟文件: {e}")
print("提示:請確保文件未被Microsoft Word佔用(關閉Word後重試)")
sys.exit(1)
# 模板配置
TEMPLATES = {
"academic": {
"h1_size": 18, "h2_size": 16, "h3_size": 14, "body_size": 12,
"h1_font": "黑體", "h2_font": "黑體", "body_font": "宋體",
"line_spacing": 1.5, "space_after": 6
},
"business": {
"h1_size": 16, "h2_size": 14, "h3_size": 12, "body_size": 11,
"h1_font": "微軟雅黑", "h2_font": "微軟雅黑", "body_font": "微軟雅黑",
"line_spacing": 1.5, "space_after": 6
},
"minimal": {
"h1_size": 14, "h2_size": 12, "h3_size": 11, "body_size": 10.5,
"h1_font": "Arial", "h2_font": "Arial", "body_font": "Arial",
"line_spacing": 1.15, "space_after": 3
},
"default": {
"h1_size": 16, "h2_size": 14, "h3_size": 12, "body_size": 12,
"h1_font": "宋體", "h2_font": "宋體", "body_font": "宋體",
"line_spacing": 1.5, "space_after": 6
}
}
config = TEMPLATES.get(template, TEMPLATES["academic"])
changes_log = []
# 操作1: 格式化
if "format" in operations or "all" in operations:
print("正在格式化文件...")
count = 0
for para in doc.paragraphs:
para.paragraph_format.line_spacing = config["line_spacing"]
para.paragraph_format.space_after = Pt(config["space_after"])
para.paragraph_format.space_before = Pt(0)
if not para.style.name.startswith('Heading'):
for run in para.runs:
run.font.name = config["body_font"]
run._element.rPr.rFonts.set(qn('w:eastAsia'), config["body_font"])
run.font.size = Pt(config["body_size"])
count += 1
changes_log.append(f"格式化 {count} 個段落")
# 操作2: 應用樣式
if "styles" in operations or "all" in operations:
print("正在應用樣式模板...")
title_count = 0
for para in doc.paragraphs:
text = para.text.strip()
if not text:
continue
if re.match(r'^[第][一二三四五六七八九十\d]+[章\s]|^[\d]+\s*[、..\s]|^[((][一二三四五六七八九十]+[))]', text):
para.style = doc.styles['Heading 1']
for run in para.runs:
run.font.name = config["h1_font"]
run._element.rPr.rFonts.set(qn('w:eastAsia'), config["h1_font"])
run.font.size = Pt(config["h1_size"])
run.font.bold = True
run.font.color.rgb = RGBColor(0, 0, 0)
title_count += 1
elif re.match(r'^\d+\.\d+[\s.、]|^[((][\d一二三四五六七八九十]+[))]', text):
para.style = doc.styles['Heading 2']
for run in para.runs:
run.font.name = config["h2_font"]
run._element.rPr.rFonts.set(qn('w:eastAsia'), config["h2_font"])
run.font.size = Pt(config["h2_size"])
run.font.bold = True
title_count += 1
elif re.match(r'^\d+\.\d+\.\d+|^[((]\d+[))]', text):
para.style = doc.styles['Heading 3']
for run in para.runs:
run.font.size = Pt(config["h3_size"])
run.font.bold = True
title_count += 1
changes_log.append(f"識別並格式化 {title_count} 個標題")
# 操作3: 生成目錄
if "toc" in operations or "all" in operations:
print("正在生成目錄...")
toc_entries = []
for para in doc.paragraphs:
if para.style.name.startswith('Heading'):
level = int(para.style.name[-1]) if para.style.name[-1].isdigit() else 1
toc_entries.append((level, para.text.strip()))
if toc_entries:
first_para = doc.paragraphs[0]
toc_title = first_para.insert_paragraph_before("目錄")
toc_title.alignment = WD_ALIGN_PARAGRAPH.CENTER
for run in toc_title.runs:
run.font.size = Pt(config["h1_size"])
run.font.bold = True
run.font.name = config["h1_font"]
run._element.rPr.rFonts.set(qn('w:eastAsia'), config["h1_font"])
for level, text in toc_entries[:50]:
indent = " " * (level - 1)
entry_para = first_para.insert_paragraph_before(f"{indent}{text}")
entry_para.paragraph_format.left_indent = Inches(0.3 * (level - 1))
for run in entry_para.runs:
run.font.size = Pt(config["body_size"])
separator = first_para.insert_paragraph_before("—" * 30)
separator.alignment = WD_ALIGN_PARAGRAPH.CENTER
changes_log.append(f"生成目錄,包含 {len(toc_entries)} 個條目")
else:
changes_log.append("未檢測到標題結構,跳過目錄生成")
# 操作4: 清理
if "cleanup" in operations or "all" in operations:
print("正在清理冗餘內容...")
removed = 0
prev_empty = False
for i in range(len(doc.paragraphs) - 1, -1, -1):
para = doc.paragraphs[i]
is_empty = not para.text.strip()
if is_empty and prev_empty:
p_element = para._element
p_element.getparent().remove(p_element)
removed += 1
prev_empty = is_empty
changes_log.append(f"刪除 {removed} 個冗餘空段落")
# 儲存文件
try:
doc.save(output_path)
print(f"文件已儲存: {output_path}")
except Exception as e:
print(f"儲存失敗: {e}")
sys.exit(1)
print("
" + "="*50)
print("整理報告")
print("="*50)
for log in changes_log:
print(log)
print("="*50)
print("文件整理完成!")
#!/bin/bash
if [ -f "${output_path}" ]; then
file_size=$(ls -lh "${output_path}" | awk '{print $5}')
echo "輸出檔案: ${output_path} (${file_size})"
echo "提示:原檔案已備份,如有問題可恢復"
else
echo "錯誤:輸出檔案未生成"
exit 1
fi
整理文件 C:/Users/Desktop/畢業論文.docx,使用學術模板,執行所有操作,輸出到 C:/Users/Desktop/畢業論文_整理版.docx
格式化 C:/Docs/報告.docx,操作包括format,toc,模板用business
| 錯誤場景 | 處理方式 |
|---|---|
| 檔案不存在 | 提示檢查路徑,退出碼1 |
| 檔案格式不支援 | 提示僅支援docx/doc,退出碼1 |
| 檔案被Word佔用 | 提示關閉Word後重試,退出碼1 |
| 許可權不足 | 提示以管理員身份執行,退出碼1 |
這是一款功能較為完善的 Word 文件整理工具,勝在模板實用、操作靈活,能滿足學術、商務等多種排版需求,自動備份設計讓使用更安心。不足之處是標題識別依賴簡單規則,複雜文件可能識別不準確,缺少批次處理功能,大檔案整理時效率可能偏低。總體而言,適合日常單文件整理場景使用,但在專業度要求較高的場合還有提升空間。