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.mzph.cn/news/912373.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

网站推广视频的服务方案网站建设技术列表

连接ESP8266开发板到电脑 虚拟机选择开发板硬件连接 查看USB连接情况: lsusb 授权USB接口访问 成功连接 编译项目 上传到开发板 成功提供WIFI热点服务

荆门做网站公众号的公司企业网站备案网址

前言 最近我在Vue 3.3的项目中对Vant4做按需导入时&#xff0c;尽管按照Vant4的官方指南进行操作&#xff0c;但样式仍然无法正确加载。经过深入研究和多篇文章的比较&#xff0c;我终于找到了在Vue3中如何正确的按需导入Vant 4组件和样式的方法。由于Vue3.3和Vant4相对较新&am…

服务器创建多个网站吗seo引擎搜索

5. 命令 本部分描述了 LAMMPS 输入脚本的格式以及其中的命令如何用于定义 LAMMPS 模拟。主要包括以下内容。 5.1. LAMMPS 输入脚本 5.2.输入脚本的解析规则 5.3.输入脚本结构 本部分描述了典型的 LAMMPS 输入脚本的结构。 LAMMPS 发行版中的示例目录包含许多示例输入脚本…

不注册公司可以做网站吗wordpress文学模板

文章转载&#xff1a; https://www.howtoforge.com/tutorial/how-to-install-oracle-database-12c-on-centos-7/

居家养老网站建设wordpress侧边栏折叠

聚沙成塔每天进步一点点 ⭐ 专栏简介⭐ 原型&#xff08;Prototype&#xff09;和原型链&#xff08;Prototype Chain&#xff09;⭐ 原型&#xff08;Prototype&#xff09;⭐ 原型链&#xff08;Prototype Chain&#xff09;⭐ 继承属性和方法⭐ 写在最后 ⭐ 专栏简介 前端入…

做企业网站都需要注意哪点赤峰seo

在平时&#xff0c;我们经常会碰到让一个div框针对某个模块上下左右都居中&#xff08;水平垂直居中&#xff09;&#xff0c;其实针对这种情况&#xff0c;我们有多种方法实现。 方法一: 绝对定位方法&#xff1a;不确定当前div的宽度和高度&#xff0c;采用 transform: trans…

商城网站开发多在上海做兼职去哪个网站搜索

现如今&#xff0c;随着网络技术的进步&#xff0c;许多的场合都会需要光纤收发器进行远距离的传输&#xff0c;以致于现在国外和国内生产光纤收发器厂商非常多&#xff0c;产品线也极为丰富。收发器都是电转光的网络结构。接下来我们就来为大家详细介绍下单模光纤收发器以及光…

做女装代理需要自建网站么设计师网站接单

STM32 PVD掉电检测功能的使用方法 前言 在实际应用场景中&#xff0c;可能会出现设备电源电压异常下降或掉电的情况&#xff0c;因此&#xff0c;有时候需要检测设备是否掉电&#xff0c;或者在设备掉电的瞬间做一些紧急关机处理&#xff0c;比如保存重要的用户数据&#xff…

VMware ESXi 磁盘置备类型详解

VMware ESXi 磁盘置备类型详解在平时运维VMware ESXi虚拟化环境时,经常要创建虚拟机,而创建虚拟机必要的操作之一是配置磁盘。而磁盘的制备方式有三种类型分别为:精简置备、厚置备延迟置零和厚置备置零,许多用户往…

EF 数据迁移生成sql脚本

创建迁移add migration xxxx生成sqlScript Migration xxx xxxx

HWiNFO 硬件信息检测工具下载与安装教程

软件介绍 HWiNFO是一款专业且全面的硬件信息检测工具,自1996年发布以来持续更新,被广泛用于硬件分析、性能优化和故障诊断。该工具支持检测CPU、主板、内存、显卡、硬盘、显示器、声卡、网卡等几乎所有硬件组件的详细…

第七章 手写数字识别V1

# 导入必要的库 import numpy as np import os import struct import matplotlib.pyplot as plt# 定义导入函数 def load_images(path):with open(path, "rb") as f:data = f.read()magic_number, num_items…

西电PCB设计指南1~2章学习笔记

西电PCB设计指南1~2章学习笔记 一、引言部分三大主流PCB设计软件:AD、PADS、Candence 好像现在还有:kicad、嘉立创EDA等等会用软件,能够 “布通 ”是远远不够的!二、PCB基础知识PCB的组成和概念PCB的内部结构PCB易…

南昌建设企业网站公司网站开发工程师要考什么证

2011 年 3 月 31 日&#xff0c;美国网络社区 Reddit 发起“世界备份日&#xff08;World Backup Day&#xff09;”倡议活动&#xff0c;号召人们做好数据安全备份。于是每年愚人节前一天成为“世界备份日”&#xff0c;口号很有趣 Don’t Be An April Fool,Backup Your Data&…

广州做网站技术响应式网站开发方法

前言 PWA做为一门Google推出的WEB端的新技术&#xff0c;好处不言而喻&#xff0c;但目前对于相关方面的知识不是很丰富&#xff0c;这里我推出一下这方面的入门教程系列&#xff0c;提供PWA方面学习。 什么是PWA PWA全称Progressive Web App&#xff0c;直译是渐进式WEB应用…

容桂网站制作值得信赖公司怎么建设官网

目录 引言 统一异常处理 异常全部监测 引言 将异常处理逻辑集中到一个地方&#xff0c;可以避免在每个控制器或业务逻辑中都编写相似的异常处理代码&#xff0c;这降低了代码的冗余&#xff0c;提高了代码的可维护性统一的异常处理使得调试和维护变得更加容易&#xff0c;通…

网站建设公司西安重庆找工作哪个网站好

登录流程图 示例预览 构建步骤 当然&#xff0c;你也可以直接之前前往coding仓库查看源码&#xff0c;要是发现bug记得提醒我啊~ LoginDemo地址 1. 首先你得有一个项目 2. 然后你需要一个登录页面 完整Login.cshtml视图代码戳这里-共计55行 效果预览图 <!DOCTYPE html>&l…

怎么通过域名访问网站彩票网站开发教程

在电商领域&#xff0c;能够快速且准确地获取商品数据是至关重要的。淘宝作为中国领先的电商平台&#xff0c;通过其开放的API接口为商家们提供了强大的数据服务功能。本文将验证如何高效地利用淘宝API接口获取商品数据&#xff0c;并提供一套行之有效的策略和步骤。 预备工作…

手机网站制作方案响应式网页设计ppt

&#xff08;注&#xff1a;因为把第七讲和第八讲放在一起了&#xff0c;主要是对那两节的了解&#xff0c;简单应用&#xff0c;没太深究&#xff01;不过全景视图和枢轴视图真的效果很不错&#xff01;&#xff09; Express Blend工具&#xff1a; 本节主讲&#xff1a;对微软…

网站数据库搬家wordpress 酷炫分页

思路 构建一个单调递增的队列类型&#xff0c;pop和push操作在队列内部进行特殊定义&#xff08;队头存储当前滑动窗口的最大值&#xff1b;队列中比插入元素小的队尾元素均要移除&#xff1b;比队尾元素小的元素直接插入队列&#xff1b;当滑动窗口移除的元素和队头元素相等时…