一、問(wèn)題的提出
有時(shí),我們手頭上有多個(gè)Excel或者Word文件,但是領(lǐng)導(dǎo)突然要求對(duì)某幾個(gè)術(shù)語(yǔ)進(jìn)行批量的修改,你是不是有要崩潰的感覺(jué)。因?yàn)檫@么多文件,要一個(gè)一個(gè)地打開(kāi)文件,再進(jìn)行批量替換修改,幾個(gè)文件還好,如果是成百上千的文件,我想你一會(huì)兒就感覺(jué)自己被搞暈了,不僅搞不清修改了沒(méi)有修改完,而且已經(jīng)修改的也不知道修改的徹底不。
于是,問(wèn)題來(lái)了,當(dāng)我需要對(duì)多個(gè)Excel和Word文件中的關(guān)鍵字進(jìn)行替換,而且不改變?cè)募母袷?,同時(shí)刪除源文件,我們?cè)撛趺崔k?這些office文件可能分布在不同的文件夾下,所以替換后還要存放在原來(lái)的文件夾。同時(shí),我們編寫(xiě)的程序還要在Windows和MacOS環(huán)境下都可以使用。
二、算法分析
由于要在多個(gè)環(huán)境下使用,我們放棄VBA,考慮采用Python編程的方法來(lái)解決。
1. 第一步?讀取一個(gè)替換關(guān)鍵字的"批量替換表.xlsx"生成一個(gè)字典,這樣是為了后面可以批量替換。第二步 遍歷當(dāng)前目錄下所有目錄包括上當(dāng)?shù)奈募?,主要是docx和xlsx文件,如果是doc和xls文件,還要考慮兩這兩種格式的文件進(jìn)行批量的轉(zhuǎn)化,見(jiàn)下面的文章 。
批量轉(zhuǎn)doc和xls為docx和xlsx文件
2. 第二步是 遍歷當(dāng)前所有目錄中的文件,用if條件,根據(jù)文件擴(kuò)展名的不同來(lái)篩選出docx和xlsx文件。代碼如下:
for root, filefolder, files in os.walk(os.curdir):
for file in files:
if file.endswith("docx"):
file_path = os.path.join(root, file)
for key, value in dic.items():
word_replace_keywords(file_path, key, value)
elif file.endswith("xlsx") and os.path.basename(file)!="批量替換表.xlsx":
file_path = os.path.join(root, file)
for key, value in dic.items():
excel_replace_keywords(file_path, key, value)
3. 第三步是對(duì)于docx和xlsx文件分別進(jìn)行替換處理,主要采用了python-docx和openpyxls這兩個(gè)模塊來(lái)進(jìn)行替換。針對(duì)docx文件,我們用Document()來(lái)讀取,用以下代碼來(lái)替換:
def info_update(doc, old, new):
for para in doc.paragraphs:
for run in para.runs:
if old in run.text:
run.text = run.text.replace(old, new)
對(duì)于xlsx文件我,我們通過(guò)下面的代碼實(shí)現(xiàn)關(guān)鍵字替換,同時(shí)不改變?cè)瓉?lái)關(guān)鍵字的格式。
def replace_cell_text_with_format(cell, keyword, replacement):
paragraphs = cell.paragraphs
for paragraph in paragraphs:
for run in paragraph.runs:
if keyword in run.text:
new_text = run.text.replace(keyword, replacement)
run.clear() # 清除當(dāng)前文本
new_run = run._element # 創(chuàng)建新的run
new_run.text = new_text # 設(shè)置新文本
for key in run._r.attrib.keys(): # 復(fù)制格式屬性
if key != 't':
new_run.attrib[key] = run._r.attrib[key]
4. 第四步?我們要保存替換后的文件,同時(shí)用os.remove()刪除原來(lái)的文件。
三、代碼展示
最終,我們編制出70多行的代碼,一鍵實(shí)現(xiàn)了多文件、多關(guān)鍵字、保存源格式,又能在Windows和蘋(píng)果電腦環(huán)境使用的程序。代碼如下:
import os
from docx import Document
from openpyxl import load_workbook
def info_update(doc, old, new):
for para in doc.paragraphs:
for run in para.runs:
if old in run.text:
run.text = run.text.replace(old, new)
def replace_cell_text_with_format(cell, keyword, replacement):
paragraphs = cell.paragraphs
for paragraph in paragraphs:
for run in paragraph.runs:
if keyword in run.text:
new_text = run.text.replace(keyword, replacement)
run.clear() # 清除當(dāng)前文本
new_run = run._element # 創(chuàng)建新的run
new_run.text = new_text # 設(shè)置新文本
for key in run._r.attrib.keys(): # 復(fù)制格式屬性
if key != 't':
new_run.attrib[key] = run._r.attrib[key]
def get_dic():
workbook = load_workbook('批量替換表.xlsx')
sht = workbook.active
dic = {}
for c1,c2 in zip(sht["A"],sht["B"]):
if c1.value!= None and c2.value!= None:
dic[c1.value] = c2.value
return dic
def word_replace_keywords(file_path, keyword, replacement):
doc = Document(file_path)
info_update(doc, keyword, replacement)
try:
for table in doc.tables:
if not any(cell.text for row in table.rows for cell in row.cells):
continue
for row in table.rows:
for cell in row.cells:
if keyword in cell.text:
replace_cell_text_with_format(cell, keyword, replacement)
except Exception as e:
print("Error processing table:", e)
doc.save(file_path)
def excel_replace_keywords(file_path, keyword, replacement):
wb = load_workbook(file_path)
for sheet_name in wb.sheetnames:
sheet = wb[sheet_name]
for row in sheet.iter_rows():
for cell in row:
if cell.value and keyword in str(cell.value):
cell.value = str(cell.value).replace(keyword, replacement)
wb.save(file_path)
wb.close()
def get_replaced(dic):
for root, filefolder, files in os.walk(os.curdir):
for file in files:
if file.endswith("docx"):
file_path = os.path.join(root, file)
for key, value in dic.items():
word_replace_keywords(file_path, key, value)
elif file.endswith("xlsx") and os.path.basename(file)!="批量替換表.xlsx":
file_path = os.path.join(root, file)
for key, value in dic.items():
excel_replace_keywords(file_path, key, value)
def main():
dic = get_dic()
get_replaced(dic)
if __name__ == "__main__":
main()
以上代碼的優(yōu)勢(shì)在于:速度快,設(shè)置好關(guān)鍵字后一鍵替換,可以在多個(gè)環(huán)境下使用,相比VBA代碼,Python代碼的執(zhí)行速度更快、操作更簡(jiǎn)單、省時(shí)省力。
四、注意事項(xiàng)
1. 運(yùn)行代碼前一定要安裝Python3.9及以上版本,同時(shí)安裝openpyxl和python-docx兩個(gè)模塊。
2. 執(zhí)行程序前要把doc和xls文件分別轉(zhuǎn)化為docx和xlsx文件,這樣更方便替換。
3. 執(zhí)行前要在程序文件目錄下建立一個(gè)xlsx文件,命名為"批量替換表.xlsx",在表的A列放上要查找的關(guān)鍵字,B列放要替換的關(guān)鍵字。文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-652263.html
4. 如果有問(wèn)題,可以隨時(shí)與我聯(lián)系,也可以通過(guò)下面進(jìn)行提問(wèn)。文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-652263.html
到了這里,關(guān)于Python批量替換Excel和Word中的關(guān)鍵字的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!