Python3的docx批量替换程序

Python3的docx批量替换程序

jsdtxm@live.com

http://www.cnblogs.com/jsdtxm/

使用python-docx库,实现批量替换一个文件夹下的所有docx文件

于Python3.6 + windows 10运行通过

安装库的方法

pip install python-docx

代码如下

# -*- coding: utf-8 -*-
#Python3

from docx import Document
from docx import table
import os
import os.path

str_bth=[]                                                                       #被替换
str_thw=[]                                                                       #替换为
filenames=[]                                                                     #文件名
file_address=['']                                                                #文件夹目录

def str_judge(strange):                                                          #判断runs是否为空或纯空格
    if strange.isspace() or strange=='' :
        return False
    else :
        return True

def name_judge(filename):                                                        #判断是否为docx且不为临时文件
    if filename.find('docx') != -1:
        if filename.find('~$') == -1:
            return True
    else :
        return False

def ui_input():                                                                  #cui输入
    file_address[0]=input('文件夹:')
    if file_address[0]=='':
        file_address[0]=os.getcwd()
    str_bth.append(input('被替换的目标:'))
    str_thw.append(input('替换为:'))
    while input('是否继续添加替换内容? Y/N :')=='Y':
        str_bth.append(input('被替换的目标:'))
        str_thw.append(input('替换为:'))

def runs_replace(paragraph,bth,thw):                                             #runs的替换
    for run in paragraph.runs:
        if str_judge(run.text):
            run.text=run.text.replace(bth,thw)

def table_traversal(table,bth,thw):                                              #遍历表格并调用runs_replace替换
    for x in range(len(table.rows)):
        for y in range(len(table.columns)):
            for paragraph in table.cell(x,y).paragraphs:
                runs_replace(paragraph,bth,thw)

def wendang_replace(wendang,bth,thw):                                            #文档替换
    for paragraph in wendang.paragraphs:
        runs_replace(paragraph,bth,thw)
    #print(len(wendang.tables))
    for table in wendang.tables:
        table_traversal(table,bth,thw)

ui_input()
os.system('cls')                                                                 #清屏

print('读取到的.docx文件如下:')
for filename in os.listdir(file_address[0]):
    if name_judge(filename):
        filenames.append(filename)
        print(filename)

print('\n将这些文件中的')
for i in range(len(str_bth)):
    print(str_bth[i],'替换为',str_thw[i])

if input('是否要继续?Y/N\n')!='Y':
    exit()
os.system('cls')

print('转换开始请等待')
for i in range(len(str_bth)):
    for docx_file in filenames:
        wendang=Document(docx_file)
        print(docx_file)
        wendang_replace(wendang,str_bth[i],str_thw[i])
        wendang.save(docx_file)
        print('\t\t\t\t\t\tDone')

posted on 2018-02-05 16:53  jsdtxm  阅读(479)  评论(0)    收藏  举报

导航