Python Word實現(xiàn)批量替換文本并生成副本
任務(wù)背景
為提高辦公效率,用python試手了一個word任務(wù),要求如下:
給你一個基礎(chǔ)word文檔A,格式為docx,名字為:A.docx。A文檔中有表格和文字,要求是將里面的字符串"完成繪畫"分別替換成完成制作款式x和復(fù)習(xí)制作款式x,輸出相應(yīng)副本,命名為對應(yīng)序號增序文檔,如:1、A.docx, 2、A.docx。
要求是輸出1000份這樣的增序文檔。
編碼思路
從問題中可提煉以下實現(xiàn)思路:
初始化,輸入目標(biāo)目錄、文件命名格式、待替換源字符串、目標(biāo)字符串
支持文檔段落和表格內(nèi)容查找,支持文本替換
文本增序和命名增序處理
效果預(yù)覽:
代碼實現(xiàn)
文件名:doc_copy_replace.py
代碼如下:
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*- """ Created on Tue Oct 29 22:20:16 2024 @author: 來知曉 """ from docx import Document def read_ducment(old, new, document): # 遍歷文檔 for paragraph in document.paragraphs: for run in paragraph.runs: #替換功能 if old in run.text: run.text=run.text.replace(old,new) # 遍歷表格 for table in document.tables: for row in table.rows: for cell in row.cells: #遍歷表格段落內(nèi)容,回到上個步驟,將cell當(dāng)作paragraph處理 for paragraph in cell.paragraphs: for run in paragraph.runs: #替換功能 if old in cell.text: run.text=run.text.replace(old,new) # doc_path = r'D:\iocode\來知曉\tmp\A.docx' # doc_new_path = r'D:\iocode\來知曉\tmp\new.docx' # str_src = '完成繪畫' # str_tar_odd = '完成制作款式' # str_tar_even = '復(fù)習(xí)制作款式' # # 單樣例測試 # document = Document(doc_path) # read_ducment(str_src, str_tar, document) # document.save(doc_new_path) # 正式demo cnt = 1000 doc_new_dir = r'D:\iocode\來知曉\tmp' doc_path_origin = r'D:\iocode\來知曉\tmp\A.docx' str_src = '完成繪畫' str_tar_odd = '完成制作款式' str_tar_even = '復(fù)習(xí)制作款式' cnt_d2 = cnt // 2 str_split = '\\' for i in range(cnt_d2): k = i + 1 str_file_name = r'、A.docx' doc_new_path_odd = doc_new_dir + str_split + str(2*k-1) + str_file_name str_tar_odd_conca = str_tar_odd + str(k) document_odd = Document(doc_path_origin) read_ducment(str_src, str_tar_odd_conca, document_odd) document_odd.save(doc_new_path_odd) doc_new_path_even = doc_new_dir + str_split + str(2*k) + str_file_name str_tar_even_conca = str_tar_even + str(k) document_even = Document(doc_path_origin) read_ducment(str_src, str_tar_even_conca, document_even) document_even.save(doc_new_path_even)
到此這篇關(guān)于Python Word實現(xiàn)批量替換文本并生成副本的文章就介紹到這了,更多相關(guān)Python Word批量替換文本內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python GUI編程學(xué)習(xí)筆記之tkinter事件綁定操作詳解
這篇文章主要介紹了Python GUI編程學(xué)習(xí)筆記之tkinter事件綁定操作,結(jié)合實例形式分析了Python GUI編程tkinter事件綁定常見操作技巧與使用注意事項,需要的朋友可以參考下2020-03-03Python+Selenium實現(xiàn)短視頻自動上傳與發(fā)布的實踐
本文主要介紹了Python+Selenium實現(xiàn)短視頻自動上傳與發(fā)布的實踐,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-04-04