• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

Python批量替换Excel和Word的关键字

武飞扬头像
PythonFun
帮助1

一、问题的提出

有时,我们手头上有多个Excel或者Word文件,但是领导突然要求对某几个术语进行批量的修改,你是不是有要崩溃的感觉。因为这么多文件,要一个一个地打开文件,再进行批量替换修改,几个文件还好,如果是成百上千的文件,我想你一会儿就感觉自己被搞晕了,不仅搞不清修改了没有修改完,而且已经修改的也不知道修改的彻底不。

于是,问题来了,当我需要对多个Excel和Word文件中的关键字进行替换,而且不改变原文件的格式,同时删除源文件,我们该怎么办?这些office文件可能分布在不同的文件夹下,所以替换后还要存放在原来的文件夹。同时,我们编写的程序还要在Windows和MacOS环境下都可以使用。

二、算法分析

由于要在多个环境下使用,我们放弃VBA,考虑采用Python编程的方法来解决。

1. 第一步 读取一个替换关键字的"批量替换表.xlsx"生成一个字典,这样是为了后面可以批量替换。第二步 遍历当前目录下所有目录包括上当的文件,主要是docx和xlsx文件,如果是doc和xls文件,还要考虑两这两种格式的文件进行批量的转化,见下面的文章 。

批量转doc和xls为docx和xlsx文件

2. 第二步是 遍历当前所有目录中的文件,用if条件,根据文件扩展名的不同来筛选出docx和xlsx文件。代码如下:

  1.  
    for root, filefolder, files in os.walk(os.curdir):
  2.  
    for file in files:
  3.  
    if file.endswith("docx"):
  4.  
    file_path = os.path.join(root, file)
  5.  
    for key, value in dic.items():
  6.  
    word_replace_keywords(file_path, key, value)
  7.  
    elif file.endswith("xlsx") and os.path.basename(file)!="批量替换表.xlsx":
  8.  
    file_path = os.path.join(root, file)
  9.  
    for key, value in dic.items():
  10.  
    excel_replace_keywords(file_path, key, value)

3. 第三步是对于docx和xlsx文件分别进行替换处理,主要采用了python-docx和openpyxls这两个模块来进行替换。针对docx文件,我们用Document()来读取,用以下代码来替换:

  1.  
    def info_update(doc, old, new):
  2.  
    for para in doc.paragraphs:
  3.  
    for run in para.runs:
  4.  
    if old in run.text:
  5.  
    run.text = run.text.replace(old, new)

对于xlsx文件我,我们通过下面的代码实现关键字替换,同时不改变原来关键字的格式。

  1.  
    def replace_cell_text_with_format(cell, keyword, replacement):
  2.  
    paragraphs = cell.paragraphs
  3.  
    for paragraph in paragraphs:
  4.  
    for run in paragraph.runs:
  5.  
    if keyword in run.text:
  6.  
    new_text = run.text.replace(keyword, replacement)
  7.  
    run.clear() # 清除当前文本
  8.  
    new_run = run._element # 创建新的run
  9.  
    new_run.text = new_text # 设置新文本
  10.  
    for key in run._r.attrib.keys(): # 复制格式属性
  11.  
    if key != 't':
  12.  
    new_run.attrib[key] = run._r.attrib[key]

4. 第四步 我们要保存替换后的文件,同时用os.remove()删除原来的文件。

三、代码展示

最终,我们编制出70多行的代码,一键实现了多文件、多关键字、保存源格式,又能在Windows和苹果电脑环境使用的程序。代码如下:

  1.  
    import os
  2.  
    from docx import Document
  3.  
    from openpyxl import load_workbook
  4.  
     
  5.  
    def info_update(doc, old, new):
  6.  
    for para in doc.paragraphs:
  7.  
    for run in para.runs:
  8.  
    if old in run.text:
  9.  
    run.text = run.text.replace(old, new)
  10.  
     
  11.  
    def replace_cell_text_with_format(cell, keyword, replacement):
  12.  
    paragraphs = cell.paragraphs
  13.  
    for paragraph in paragraphs:
  14.  
    for run in paragraph.runs:
  15.  
    if keyword in run.text:
  16.  
    new_text = run.text.replace(keyword, replacement)
  17.  
    run.clear() # 清除当前文本
  18.  
    new_run = run._element # 创建新的run
  19.  
    new_run.text = new_text # 设置新文本
  20.  
    for key in run._r.attrib.keys(): # 复制格式属性
  21.  
    if key != 't':
  22.  
    new_run.attrib[key] = run._r.attrib[key]
  23.  
    def get_dic():
  24.  
    workbook = load_workbook('批量替换表.xlsx')
  25.  
    sht = workbook.active
  26.  
    dic = {}
  27.  
    for c1,c2 in zip(sht["A"],sht["B"]):
  28.  
    if c1.value!= None and c2.value!= None:
  29.  
    dic[c1.value] = c2.value
  30.  
    return dic
  31.  
     
  32.  
    def word_replace_keywords(file_path, keyword, replacement):
  33.  
    doc = Document(file_path)
  34.  
    info_update(doc, keyword, replacement)
  35.  
    try:
  36.  
    for table in doc.tables:
  37.  
    if not any(cell.text for row in table.rows for cell in row.cells):
  38.  
    continue
  39.  
    for row in table.rows:
  40.  
    for cell in row.cells:
  41.  
    if keyword in cell.text:
  42.  
    replace_cell_text_with_format(cell, keyword, replacement)
  43.  
    except Exception as e:
  44.  
    print("Error processing table:", e)
  45.  
     
  46.  
    doc.save(file_path)
  47.  
     
  48.  
    def excel_replace_keywords(file_path, keyword, replacement):
  49.  
    wb = load_workbook(file_path)
  50.  
    for sheet_name in wb.sheetnames:
  51.  
    sheet = wb[sheet_name]
  52.  
    for row in sheet.iter_rows():
  53.  
    for cell in row:
  54.  
    if cell.value and keyword in str(cell.value):
  55.  
    cell.value = str(cell.value).replace(keyword, replacement)
  56.  
    wb.save(file_path)
  57.  
    wb.close()
  58.  
     
  59.  
    def get_replaced(dic):
  60.  
    for root, filefolder, files in os.walk(os.curdir):
  61.  
    for file in files:
  62.  
    if file.endswith("docx"):
  63.  
    file_path = os.path.join(root, file)
  64.  
    for key, value in dic.items():
  65.  
    word_replace_keywords(file_path, key, value)
  66.  
    elif file.endswith("xlsx") and os.path.basename(file)!="批量替换表.xlsx":
  67.  
    file_path = os.path.join(root, file)
  68.  
    for key, value in dic.items():
  69.  
    excel_replace_keywords(file_path, key, value)
  70.  
    def main():
  71.  
    dic = get_dic()
  72.  
    get_replaced(dic)
  73.  
    if __name__ == "__main__":
  74.  
    main()
学新通

以上代码的优势在于:速度快,设置好关键字后一键替换,可以在多个环境下使用,相比VBA代码,Python代码的执行速度更快、操作更简单、省时省力。

四、注意事项

1. 运行代码前一定要安装Python3.9及以上版本,同时安装openpyxl和python-docx两个模块。

2. 执行程序前要把doc和xls文件分别转化为docx和xlsx文件,这样更方便替换。

3. 执行前要在程序文件目录下建立一个xlsx文件,命名为"批量替换表.xlsx",在表的A列放上要查找的关键字,B列放要替换的关键字。

4. 如果有问题,可以随时与我联系,也可以通过下面进行提问。

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhihbiie
系列文章
更多 icon
同类精品
更多 icon
继续加载