白嫖一份Python代码,批量处理Word文档(.doc/.docx)——批量获取文档标题并以标题重命名文件?
import os
import time
from docx import Document
from win32com import client as wc # 导入win32com.client模块并设置别名wc
def 另存为(): # 模块docx不支持对doc文件的修改,先另存一下.直接改后缀名是不行的.
name = os.path.splitext(file_name_list[file]) # os.path.splitext(): 分离文件名与扩展名,用name[0]只取文件名docx = word.Documents.Open(ul + "\\" + file_name_list[file]) # 打开文件
docx.SaveAs(ul + "\\" + name[0] + ".docx", 16) # 另存为.docx
docx.Close() # 随开随关
def 重命名():
name = os.path.splitext(file_name_list[file]) # os.path.splitext(): 分离文件名与扩展名,用name[0]只取文件名if name[1] == '.docx': # 对docx文件的操作
docx = word.Documents.Open(ul + "\\" + file_name_list[file]) # 打开文件
docx2 = Document(ul + "\\" + file_name_list[file]) # 建立文本对象
s = docx2.tables[0].rows[2].cells[0].text # 获取文章内数据,大致翻译为 文本对象的第一个表格的第三行的第一个元素的文本内容
a = s.find("已完成") # 开始对获取的字符串文本做切片工作,找到目标文本
b = s.find("内容")
c = s.find("部位")
ret = s[a:b]
ret = ret.split(")")
ret = ret[0].split("(")
rat = s[c + 2:b]
rename = ret[1] + "_" + rat.strip() + "_" + name[0][5:] # 将目标文本赋值存起来
docx.SaveAs(ul + "\\" + rename.strip() + ".docx", 16) # 先把文本中的空格去掉(strip),然后另存为.docx
docx.Close() # 随用随关
os.remove(ul + "\\" + name[0] + ".doc")
os.remove(ul + "\\" + name[0] + ".docx")
start = time.time() # 记录程序开始时间
word = wc.Dispatch("Word.Application") # 打开 office-word应用
ul = r"F:\ceshidemo" # 设置需要处理的文件所在文件夹目录,使用/或\
docx_num = 0
file_name_list = os.listdir(ul) # 将文件夹目录下的文件名放入列表
for file in range(len(file_name_list)): # for循环开始处理文件,判断下文件是不是已经处理过了
name0 = os.path.splitext(file_name_list[file]) # os.path.splitext(): 分离文件名与扩展名,用name[0]只取文件名if name0[1] == '.docx':
docx_num += 1
if not docx_num: # 如果文件没被处理过
file_name_list = os.listdir(ul) # 将文件夹目录下的文件名放入列表for file in range(len(file_name_list)): # for循环开始处理文件,另存为
另存为()
file_name_list = os.listdir(ul) # 将文件夹目录下的文件名放入列表
for file in range(len(file_name_list)): # for循环开始处理文件,重命名
重命名()
word.Quit()
stop = time.time() # 记录程序结束时间
print(stop-start) # 打印时间
for i in range(2):
ul = r"D:\Users\liuzh\Desktop\报验\开挖初支\一工区\资料\资料\一工区测量开挖放样资料全部\2.0" # 设置需要处理的文件所在文件夹目录,使用/或\
file_name_list = os.listdir(ul) # 将文件夹目录下的文件名放入列表
print(len(file_name_list)) # 瞄一眼文件数量对不对
for file in range(len(file_name_list)): # for循环开始处理文件,python3没有xrange了
docx = word.Documents.Open(ul + "\" + file_name_list[file]) # 打开文件
name = os.path.splitext(file_name_list[file]) # os.path.splitext(): 分离文件名与扩展名,用name[0]只取文件名
if name[1] == ".docx":
docx2 = Document(ul + "\" + file_name_list[file])
s = docx2.tables[0].rows[2].cells[0].text
a = s.find("已完成")
b = s.find("内容")
c = s.find("部位")
ret = s[a:b]
ret = ret.split(")")
ret = ret[0].split("(")
rat = s[c + 2:b]
rename = ret[1] + "_" + rat.strip() + "_" + name0
docx.SaveAs(ul + "\" + rename.strip() + ".docx", 16) # 另存为.docx
docx.Close()
os.remove(ul + "\" + name[0] + ".doc")
os.remove(ul + "\" + name[0] + ".docx")
else:
docx.SaveAs(ul + "\" + name[0] + ".docx", 16) # 另存为.docx
docx.Close()
word.Quit()
以上是 白嫖一份Python代码,批量处理Word文档(.doc/.docx)——批量获取文档标题并以标题重命名文件? 的全部内容, 来源链接: utcz.com/p/938959.html