当前位置: 首页 > news >正文

Word文档内容批量替换脚本 - wanghongwei

word_replace_v1.py

# -*- coding: utf-8 -*-
"""
Word文档批量替换脚本功能说明:
1. 递归处理当前目录及所有子目录中的Word文档(.docx格式)
2. 将文档中的指定文本替换为新文本,同时保留原有格式
3. 支持处理段落和表格中的文本使用方法:
1. 基本使用:python word_replace.py --old "原文本" --new "新文本"
2. 指定目录:python word_replace.py --dir "/path/to/docs" --old "原文本" --new "新文本"
3. 查看帮助:python word_replace.py --help注意事项:
- 需要安装python-docx库:pip install python-docx
- 仅支持.docx格式,不支持旧的.doc格式
- 会直接修改原文件,建议先备份重要文档
- 如果文本跨多个格式块(run),可能无法完全替换示例:
python word_replace.py --old "公司A" --new "公司B"
python word_replace.py --dir "./项目文档" --old "2023年" --new "2024年"
"""import os
import argparse
from docx import Documentdef replace_in_docx(file_path, old_text, new_text):"""在单个Word文档中替换文本,保留格式参数:file_path: Word文档路径old_text: 要替换的旧文本new_text: 替换后的新文本"""doc = Document(file_path)# 替换段落中的文本for paragraph in doc.paragraphs:if old_text in paragraph.text:for run in paragraph.runs:if old_text in run.text:run.text = run.text.replace(old_text, new_text)# 替换表格中的文本for table in doc.tables:for row in table.rows:for cell in row.cells:for paragraph in cell.paragraphs:if old_text in paragraph.text:for run in paragraph.runs:if old_text in run.text:run.text = run.text.replace(old_text, new_text)doc.save(file_path)print(f'已处理: {file_path}')def process_all_word_files(directory, old_text, new_text):"""递归处理所有Word文档参数:directory: 要处理的目录路径old_text: 要替换的旧文本new_text: 替换后的新文本"""processed_count = 0error_count = 0for root, dirs, files in os.walk(directory):for file in files:if file.endswith('.docx'):file_path = os.path.join(root, file)try:replace_in_docx(file_path, old_text, new_text)processed_count += 1except Exception as e:error_count += 1print(f'处理失败 {file_path}: {e}')print(f'\n处理完成!成功处理 {processed_count} 个文档,失败 {error_count} 个文档')def main():"""主函数"""parser = argparse.ArgumentParser(description='Word文档批量替换脚本 - 递归替换所有Word文档中的文本并保留格式',formatter_class=argparse.RawDescriptionHelpFormatter,epilog='''
示例:%(prog)s --old "公司A" --new "公司B"%(prog)s --dir "./项目文档" --old "2023年" --new "2024年"%(prog)s --dir "." --old "旧版本" --new "新版本" --dry-run注意:- 需要安装python-docx库: pip install python-docx- 仅支持.docx格式,不支持旧的.doc格式- 默认会直接修改原文件,使用--dry-run参数可预览而不实际修改''')parser.add_argument('--dir', default='.', help='要处理的目录路径(默认当前目录)')parser.add_argument('--old', required=True, help='要替换的旧文本(必填)')parser.add_argument('--new', required=True, help='替换后的新文本(必填)')parser.add_argument('--dry-run', action='store_true',help='预览模式,显示将要修改的文件但不实际执行替换')args = parser.parse_args()# 检查目录是否存在if not os.path.exists(args.dir):print(f"错误:目录 '{args.dir}' 不存在")return# 如果是预览模式,只显示将要处理的文件if args.dry_run:print("预览模式(不会实际修改文件):")docx_files = []for root, dirs, files in os.walk(args.dir):for file in files:if file.endswith('.docx'):file_path = os.path.join(root, file)docx_files.append(file_path)print(f"  {file_path}")if docx_files:print(f"\n找到 {len(docx_files)} 个Word文档,将替换文本: '{args.old}' -> '{args.new}'")else:print("未找到任何Word文档(.docx)")return# 执行实际替换操作print(f"开始处理目录: {args.dir}")print(f"替换文本: '{args.old}' -> '{args.new}'")process_all_word_files(args.dir, args.old, args.new)if __name__ == '__main__':main()

word_replace_v2.py

#!/usr/bin/env python3
"""
Word文档批量替换脚本 - 增强版功能说明:
1. 递归处理当前目录及所有子目录中的Word文档(.docx格式)
2. 将文档中的指定文本替换为新文本,同时保留原有格式
3. 支持处理段落和表格中的文本
4. 增强功能:能够处理跨多个格式块(run)的文本替换使用方法:
1. 基本使用:python word_replace.py --old "原文本" --new "新文本"
2. 指定目录:python word_replace.py --dir "/path/to/docs" --old "原文本" --new "新文本"
3. 查看帮助:python word_replace.py --help注意事项:
- 需要安装python-docx库:pip install python-docx
- 仅支持.docx格式,不支持旧的.doc格式
- 会直接修改原文件,建议先备份重要文档
- 增强版能够处理跨多个格式块的文本替换示例:
python word_replace.py --old "公司A" --new "公司B"
python word_replace.py --dir "./项目文档" --old "2023年" --new "2024年"
"""import os
import argparse
from docx import Document
from docx.shared import Pt
from docx.enum.text import WD_COLOR_INDEXdef find_text_in_runs(paragraph, old_text):"""在段落的所有run中查找文本,处理跨多个run的情况参数:paragraph: 段落对象old_text: 要查找的文本返回:包含匹配信息的字典,或None如果未找到"""full_text = paragraph.textif old_text not in full_text:return None# 查找文本在完整段落中的位置start_idx = full_text.find(old_text)end_idx = start_idx + len(old_text)# 确定哪些run包含了目标文本run_start_idx = 0matching_runs = []for run in paragraph.runs:run_end_idx = run_start_idx + len(run.text)# 检查这个run是否包含目标文本的一部分if run_start_idx <= start_idx < run_end_idx or \run_start_idx < end_idx <= run_end_idx or \(start_idx <= run_start_idx and run_end_idx <= end_idx):matching_runs.append({'run': run,'run_start': run_start_idx,'run_end': run_end_idx,'text_start': max(start_idx, run_start_idx),'text_end': min(end_idx, run_end_idx)})run_start_idx = run_end_idxif not matching_runs:return Nonereturn {'matching_runs': matching_runs,'text_start': start_idx,'text_end': end_idx,'old_text': old_text}def replace_text_in_paragraph(paragraph, old_text, new_text):"""替换段落中的文本,处理跨多个run的情况参数:paragraph: 段落对象old_text: 要替换的旧文本new_text: 替换后的新文本"""match_info = find_text_in_runs(paragraph, old_text)if not match_info:return False# 如果文本只在一个run中,直接替换if len(match_info['matching_runs']) == 1:run_info = match_info['matching_runs'][0]run = run_info['run']# 计算文本在run中的位置run_local_start = run_info['text_start'] - run_info['run_start']run_local_end = run_info['text_end'] - run_info['run_start']# 替换文本run.text = run.text[:run_local_start] + new_text + run.text[run_local_end:]return True# 处理跨多个run的文本替换# 策略:保留第一个run的格式,将替换后的文本放入第一个run,删除其他run中的相关内容# 获取第一个匹配的runfirst_run_info = match_info['matching_runs'][0]first_run = first_run_info['run']# 计算在第一个run中的文本位置first_run_local_start = first_run_info['text_start'] - first_run_info['run_start']# 构建新文本# 第一个run中目标文本之前的部分 + 新文本new_run_text = first_run.text[:first_run_local_start] + new_text# 更新第一个run的文本first_run.text = new_run_text# 处理后续的run:删除它们中包含的目标文本部分for i, run_info in enumerate(match_info['matching_runs']):if i == 0:  # 第一个run已经处理过continuerun = run_info['run']run_local_start = run_info['text_start'] - run_info['run_start']run_local_end = run_info['text_end'] - run_info['run_start']# 如果这个run只包含目标文本的一部分,删除这部分if run_local_end < len(run.text):run.text = run.text[run_local_end:]else:# 如果整个run都是目标文本的一部分,清空它run.text = ""return Truedef replace_in_docx(file_path, old_text, new_text):"""在单个Word文档中替换文本,处理跨多个格式块的情况参数:file_path: Word文档路径old_text: 要替换的旧文本new_text: 替换后的新文本"""doc = Document(file_path)replaced_count = 0# 替换段落中的文本for paragraph in doc.paragraphs:if old_text in paragraph.text:if replace_text_in_paragraph(paragraph, old_text, new_text):replaced_count += 1# 替换表格中的文本for table in doc.tables:for row in table.rows:for cell in row.cells:for paragraph in cell.paragraphs:if old_text in paragraph.text:if replace_text_in_paragraph(paragraph, old_text, new_text):replaced_count += 1if replaced_count > 0:doc.save(file_path)print(f'已处理: {file_path} (替换了 {replaced_count} 处)')else:print(f'跳过: {file_path} (未找到匹配文本)')def process_all_word_files(directory, old_text, new_text):"""递归处理所有Word文档参数:directory: 要处理的目录路径old_text: 要替换的旧文本new_text: 替换后的新文本"""processed_count = 0error_count = 0for root, dirs, files in os.walk(directory):for file in files:if file.endswith('.docx'):file_path = os.path.join(root, file)try:replace_in_docx(file_path, old_text, new_text)processed_count += 1except Exception as e:error_count += 1print(f'处理失败 {file_path}: {e}')print(f'\n处理完成!成功处理 {processed_count} 个文档,失败 {error_count} 个文档')def main():"""主函数"""parser = argparse.ArgumentParser(description='Word文档批量替换脚本 - 增强版,支持跨格式块文本替换',formatter_class=argparse.RawDescriptionHelpFormatter,epilog='''
示例:%(prog)s --old "公司A" --new "公司B"%(prog)s --dir "./项目文档" --old "2023年" --new "2024年"%(prog)s --dir "." --old "旧版本" --new "新版本" --dry-run注意:- 需要安装python-docx库: pip install python-docx- 仅支持.docx格式,不支持旧的.doc格式- 默认会直接修改原文件,使用--dry-run参数可预览而不实际修改- 增强版能够处理跨多个格式块的文本替换''')parser.add_argument('--dir', default='.', help='要处理的目录路径(默认当前目录)')parser.add_argument('--old', required=True, help='要替换的旧文本(必填)')parser.add_argument('--new', required=True, help='替换后的新文本(必填)')parser.add_argument('--dry-run', action='store_true',help='预览模式,显示将要修改的文件但不实际执行替换')args = parser.parse_args()# 检查目录是否存在if not os.path.exists(args.dir):print(f"错误:目录 '{args.dir}' 不存在")return# 如果是预览模式,只显示将要处理的文件if args.dry_run:print("预览模式(不会实际修改文件):")docx_files = []for root, dirs, files in os.walk(args.dir):for file in files:if file.endswith('.docx'):file_path = os.path.join(root, file)docx_files.append(file_path)print(f"  {file_path}")if docx_files:print(f"\n找到 {len(docx_files)} 个Word文档,将替换文本: '{args.old}' -> '{args.new}'")else:print("未找到任何Word文档(.docx)")return# 执行实际替换操作print(f"开始处理目录: {args.dir}")print(f"替换文本: '{args.old}' -> '{args.new}'")print("增强模式:支持跨多个格式块的文本替换")process_all_word_files(args.dir, args.old, args.new)if __name__ == '__main__':main()
http://www.hskmm.com/?act=detail&tid=14508

相关文章:

  • VMware ESXi 磁盘置备类型详解
  • EF 数据迁移生成sql脚本
  • HWiNFO 硬件信息检测工具下载与安装教程
  • 第七章 手写数字识别V1
  • 西电PCB设计指南1~2章学习笔记
  • 1. 大模型的选择详细分析 - Rainbow
  • 云计算实践部署笔记
  • [eJOI 2024] 奶酪交易 / Cheese
  • 逆向分析之switch语句
  • 批量查询设计桩号方法及文件格式
  • 搭建Python的运行开发环境
  • 【HBase 原理部署安装 01】
  • 打破数据壁垒,DMS Data Agent 开启智能分析之旅
  • Ruby IPAddr正则表达式拒绝服务漏洞分析与修复
  • 模型驱动的 AI Agent架构:亚马逊云科技的Strands框架技术深度解析
  • cache支持的软件操作
  • PHP 静态分析工具实战 PHPStan 和 Psalm 完全指南
  • tests-stats/regression.sh
  • 光隔离探头技术解析:高电压测量的安全革命​​
  • freertos.c解析 - 教程
  • 从缺陷管理到质量协作:现代Bug工具的范式升级
  • 【html组件】简易漫画阅读器
  • ubuntu安装mysql2
  • 高并发系统核心指标
  • 工程化知识管理新范式:DevOps驱动下的智能文档体系建设实践
  • 从零开始学Flink:数据转换的艺术
  • java创建线程池去实现某个任务(多线程)
  • 20250827_黔西南网信杯_丢失的数据
  • 敏捷已死?2025年项目管理软件支持的混合管理模式正成为新主流!
  • 螺旋矩阵-leetcode