Python初学尝试:word批量刷格式转PDF,替换页眉页脚

  • 初学尝试
  • round 1
  • ronund 2 easygui
  • round 4 PyQt5
  • round 4 wxpython
  • 小结

初学尝试

之前做培训行业,做讲义做的每天头昏脑胀,正好学过一点点python,就尝试自己写个小程序来解决问题,开始写才发现,之前学的都是渣渣ಥ_ಥ
经过多番查找,摘抄,终于完工,代码80%是东摘西凑,时间太久,现在也记不清到底从哪里摘的了,实在抱歉

round 1

话不多说,先上码

import os            #导入文件操作模块
import re             #导入正则模块
import win32com  #导入word操作模块

#准备打开word
from win32com.client import Dispatch,constants#这句好像没啥用
w = win32com.client.Dispatch('Word.Application')
w.Visible = 0
w.DisplayAlerts = 0
wenjianjia1=input("输入目录")

def replace_doc(self,string,new_string):
      #替换文字
      self.Selection.Find.ClearFormatting()
      self.Selection.Find.Replacement.ClearFormatting()
      self.Selection.Find.Execute(string, False, False, True, False, False, True, 1, True, new_string, 2)


def replace_en(self):
      #格式化英文字符
      self.Selection.Find.ClearFormatting()
      self.Selection.Find.Replacement.Font.Name="Times New Roman"
      self.Selection.Find.Replacement.Font.Italic = True
      self.Selection.Find.Execute('^$', False, False, False, False, False, True, 1, True, '^&', 2)
 
      
def formate_doc(wenjianjia):     
      for root, dirnames, filenames in os.walk(wenjianjia):
              for filename in filenames:
                      if filename.endswith(".doc") or filename.endswith(".docx"):
                              classRTF = os.path.join(root,filename)
                              doc = w.Documents.Open(FileName = classRTF)
                              doc.PageSetup.PaperSize = 7 
                              doc.PageSetup.Orientation = 0

                        #1.修改全文字体、字号
                              w.ActiveDocument.Select()
                              w.Selection.Paragraphs.LineSpacing=18
                              w.Selection.Font.Bold = False
                              w.Selection.Font.Name = "宋体"
                              w.Selection.Font.Name = "Times New Roman"
                              w.Selection.Font.Size = "10.5"#五号
                              replace_doc(w,'.','。')
                        
                         

                        #前两行清除格式,主要是首行缩进
                              doc.Paragraphs(1).Range.Select()
                              w.Selection.ClearFormatting()


                        #第一行也就是标题改字体、字号、居中
                              par1 = doc.Paragraphs(1).Range
                              par1.ParagraphFormat.Reset()#取消首行缩进
                              par1.Font.Name = "黑体"
                              par1.Font.Size = "16"#三号
                              par1.ParagraphFormat.Alignment = 1
                        
                              replace_en(w)
                        
                        
                              print("已处理:" + classRTF)
                              doc.Close()
                              w.Quit
                     
formate_doc(wenjianjia1)                     
print("处理完毕!")

基本可以正常工作的,由于是终端界面,自用还行,介绍给其他同事操作不来,于是开始尝试GUI

ronund 2 easygui

先上码

import easygui as g
import os            #导入文件操作模块
import re             #导入正则模块
import win32com  #导入word操作模块


from win32com.client import Dispatch,constants
w = win32com.client.Dispatch('Word.Application')
w.Visible = 0
w.DisplayAlerts = 0



    



def replace_doc(self,string,new_string):
      '''替换文字'''
      self.Selection.Find.ClearFormatting()
      self.Selection.Find.Replacement.ClearFormatting()
      self.Selection.Find.Execute(string, False, False, True, False, False, True, 1, True, new_string, 2)


def replace_en(self):
      '''替换文字'''
      self.Selection.Find.ClearFormatting()
      self.Selection.Find.Replacement.Font.Name="Times New Roman"
      self.Selection.Find.Replacement.Font.Italic = True
      self.Selection.Find.Execute('^$', False, False, False, False, False, True, 1, True, '^&', 2)

def formate_doc(filename):
    
                              doc = w.Documents.Open(FileName = filename)
                              doc.PageSetup.PaperSize = 7 
                              doc.PageSetup.Orientation = 0

                        #1.修改正文字体、字号
                              w.ActiveDocument.Select()
                              w.Selection.Paragraphs.LineSpacing=18
                              w.Selection.Font.Bold = False
                              w.Selection.Font.Name = "宋体"
                              w.Selection.Font.Name = "Times New Roman"
                              w.Selection.Font.Size = "10.5"#五号
                              replace_doc(w,'.','。')
                        
                         

                        #前两行清除格式,主要是首行缩进
                              doc.Paragraphs(1).Range.Select()
                              w.Selection.ClearFormatting()


                        #第一行改字体、字号、居中
                              par1 = doc.Paragraphs(1).Range
                              par1.ParagraphFormat.Reset()#取消首行缩进
                              par1.Font.Name = "黑体"
                              par1.Font.Size = "16"#三号
                              par1.ParagraphFormat.Alignment = 1
                        
                              replace_en(w)#英文字符进行斜体替换
                        
                        
                              
                              doc.Close()
                              w.Quit

 
      
def formate_dir(wenjianjia):     
      for root, dirnames, filenames in os.walk(wenjianjia):
              for filename in filenames:
                  if filename.endswith(".doc") or filename.endswith(".docx"):
                              classRTF = os.path.join(root,filename)
                              formate_doc(classRTF)
                      
                     


c=g.buttonbox(msg="格式化文件", title="格式化文件", choices=("格式化文件夹", "格式化单文件","取消"))
if (c=="格式化单文件"):
    file1=g.fileopenbox(msg=None, title=None, default='*', filetypes=None)
    formate_doc(file1)
    g.msgbox("文件格式化完成")
elif (c=="格式化文件夹"):
    dir1=g.diropenbox(msg=None, title=None, default=None)
    formate_dir(dir1)
    g.msgbox("文件夹格式化完成")
else:
    g.msgbox("再见")

easygui 简单好用,就是界面有点丑,而且没找到frame窗口,后来又有了新尝试

round 4 PyQt5

先上码

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

# Form implementation generated from reading ui file 'formate.ui'
#
# Created by: PyQt5 UI code generator 5.14.1
#
# WARNING! All changes made in this file will be lost!


from PyQt5 import QtCore, QtWidgets

from PyQt5.QtWidgets import *
import sys
import os            #导入文件操作模块
import re             #导入正则模块
import win32com  #导入word操作模块



from win32com.client import Dispatch,constants
w = win32com.client.Dispatch('Word.Application')
w.Visible = 0
w.DisplayAlerts = 0







class Ui_MainWindow(QWidget):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(240, 320)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.pushButton = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton.setGeometry(QtCore.QRect(60, 40, 113, 51))
        self.pushButton.setObjectName("pushButton")
        self.pushButton_2 = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton_2.setGeometry(QtCore.QRect(60, 100, 113, 51))
        self.pushButton_2.setObjectName("pushButton_2")
        self.pushButton_3 = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton_3.setGeometry(QtCore.QRect(60, 200, 113, 61))
        self.pushButton_3.setObjectName("pushButton_3")
        MainWindow.setCentralWidget(self.centralwidget)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
        self.pushButton.setText(_translate("MainWindow", "格式化单文件"))
        self.pushButton_2.setText(_translate("MainWindow", "格式化文件夹"))
        self.pushButton_3.setText(_translate("MainWindow", "退出"))

        self.pushButton.clicked.connect(self.on_click1)
        self.pushButton_2.clicked.connect(self.on_click2)
        self.pushButton_3.clicked.connect(QtCore.QCoreApplication.instance().quit)


    def on_click1(self):
        openfile_name,filetype=QFileDialog.getOpenFileName(None)
        formate_doc(openfile_name)
        self.selectInfo("格式化文件完成")




    def on_click2(self):
        open_dir=QFileDialog.getExistingDirectory()

        formate_dir(open_dir)
        self.selectInfo("格式化文件夹完成")

    def selectInfo(self,message):
        QMessageBox.information(self,"Information",message)

def replace_doc(self, string, new_string):
        '''替换文字'''
        self.Selection.Find.ClearFormatting()
        self.Selection.Find.Replacement.ClearFormatting()
        self.Selection.Find.Execute(string, False, False, True, False, False, True, 1, True, new_string, 2)

def replace_en(self):
        '''格式化英文字符'''
        self.Selection.Find.ClearFormatting()
        self.Selection.Find.Replacement.Font.Name = "Times New Roman"
        self.Selection.Find.Replacement.Font.Italic = True
        self.Selection.Find.Execute('^$', False, False, False, False, False, True, 1, True, '^&', 2)

def formate_doc(filename1):
        filename2=convert_path(filename1)

        doc = w.Documents.Open(FileName=filename2)
        doc.PageSetup.PaperSize = 7
        doc.PageSetup.Orientation = 0

        # 1.修改正文字体、字号
        w.ActiveDocument.Select()
        w.Selection.Paragraphs.LineSpacing = 18
        w.Selection.Font.Bold = False
        w.Selection.Font.Name = "宋体"
        w.Selection.Font.Name = "Times New Roman"
        w.Selection.Font.Size = "10.5"  # 五号
        replace_doc(w, '.', '。')

        # 前两行清除格式,主要是首行缩进
        doc.Paragraphs(1).Range.Select()
        w.Selection.ClearFormatting()

        # 第一行改字体、字号、居中
        par1 = doc.Paragraphs(1).Range
        par1.ParagraphFormat.Reset()  # 取消首行缩进
        par1.Font.Name = "黑体"
        par1.Font.Size = "16"  # 三号
        par1.ParagraphFormat.Alignment = 1

        replace_en(w)  # 英文字符进行斜体替换

        doc.Close()
        w.Quit

def formate_dir(wenjianjia):
        for root, dirnames, filenames in os.walk(wenjianjia):
            for filename in filenames:
                if filename.endswith(".doc") or filename.endswith(".docx"):
                    classRTF = os.path.join(root,filename)
                    
                    formate_doc(classRTF)





def convert_path(path: str) -> str:
    seps = r'\/'
    sep_other = seps.replace(os.sep, '')
    return path.replace(sep_other, os.sep) if sep_other in path else path


if __name__ == '__main__':
    app = QApplication(sys.argv)
    MainWindow = QMainWindow()
    ui = formate.Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()

    sys.exit(app.exec_())

PyQt5有界面编辑器,很好用,就是封包后的exe文件有点大,而且win下路径支持不够好,所以找了这个代码用来转换路径,谢谢大佬的代码@Inotime

round 4 wxpython

#!/usr/bin/env python
# -*- coding: UTF-8 -*-
#
# generated by wxGlade 0.9.5 on Thu Feb 27 09:52:35 2020
#

import wx
import fontdir

import sys
import os  # 导入文件操作模块
import re  # 导入正则模块
import win32com  # 导入word操作模块


from win32com.client import Dispatch, constants

w = win32com.client.Dispatch('Word.Application')
w.Visible = 0
w.DisplayAlerts = 0

open_file = None
open_dir = None
open_file1 = None
open_dir1 = None
open_file2 = None
open_dir2 = None
font1 = "宋体"
size1 = "10.5"
font2 = "黑体"
size2 = "16"
font3 = "Times New Roman"
bl = False
It = False
w2pdf = False
doc_moban=None

# begin wxGlade: dependencies
# end wxGlade





def conver_size(size:str)->str:
    if size=="初号":
        return "42"
    elif size=="三号":
        return "16"
    elif size=="小四":
        return "12"

    elif size=="五号":
        return "10.5"


class MyFrame(wx.Frame):
    def __init__(self, *args, **kwds):
        # begin wxGlade: MyFrame.__init__
        kwds["style"] = kwds.get("style", 0) | wx.DEFAULT_FRAME_STYLE
        wx.Frame.__init__(self, *args, **kwds)
        self.SetSize((600, 400))
        self.notebook = wx.Notebook(self, wx.ID_ANY, style=wx.NB_BOTTOM)
        self.notebook_pane_1 = wx.Panel(self.notebook, wx.ID_ANY)
        self.checkbox_8 = wx.CheckBox(self.notebook_pane_1, wx.ID_ANY, u"粗体")
        self.combo_box_1 = wx.ComboBox(self.notebook_pane_1, wx.ID_ANY, choices=fontdir.fonts.fonts, style=wx.CB_DROPDOWN)
        self.combo_box_3 = wx.ComboBox(self.notebook_pane_1, wx.ID_ANY, choices=fontdir.fonts.sizes, style=wx.CB_DROPDOWN)
        self.checkbox_9 = wx.CheckBox(self.notebook_pane_1, wx.ID_ANY, "斜体")
        self.combo_box_2 = wx.ComboBox(self.notebook_pane_1, wx.ID_ANY, choices=fontdir.fonts.fonts, style=wx.CB_DROPDOWN)
        self.combo_box_4 = wx.ComboBox(self.notebook_pane_1, wx.ID_ANY, choices=fontdir.fonts.sizes, style=wx.CB_DROPDOWN)
        self.checkbox_10 = wx.CheckBox(self.notebook_pane_1, wx.ID_ANY, u"同时转换PDF")
        self.combo_box_5 = wx.ComboBox(self.notebook_pane_1, wx.ID_ANY, choices=["Times New Roman"],style=wx.CB_DROPDOWN)
        self.button_14 = wx.Button(self.notebook_pane_1, wx.ID_ANY, u"单文件")
        self.button_15 = wx.Button(self.notebook_pane_1, wx.ID_ANY, u"文件夹")
        self.button_16 = wx.Button(self.notebook_pane_1, wx.ID_ANY, u"格式化")
        self.button_17 = wx.Button(self.notebook_pane_1, wx.ID_ANY, u"退出")
        self.notebook_pane_2 = wx.Panel(self.notebook, wx.ID_ANY)
        self.notebook_pane_3 = wx.Panel(self.notebook, wx.ID_ANY)
        self.notebook_pane_2 = wx.Panel(self.notebook, wx.ID_ANY)
        self.panel_6 = wx.Panel(self.notebook_pane_2, wx.ID_ANY)
        self.panel_7 = wx.Panel(self.notebook_pane_2, wx.ID_ANY)
        self.panel_8 = wx.Panel(self.notebook_pane_2, wx.ID_ANY)
        self.button_5 = wx.Button(self.notebook_pane_2, wx.ID_ANY, u"打开单文件")
        self.button_6 = wx.Button(self.notebook_pane_2, wx.ID_ANY, u"打开文件夹")
        self.button_7 = wx.Button(self.notebook_pane_2, wx.ID_ANY, u"开始转换")
        self.panel_9 = wx.Panel(self.notebook_pane_2, wx.ID_ANY)
        self.panel_11 = wx.Panel(self.notebook_pane_2, wx.ID_ANY)
        self.panel_10 = wx.Panel(self.notebook_pane_2, wx.ID_ANY)
        self.notebook_pane_3 = wx.Panel(self.notebook, wx.ID_ANY)
        self.panel_1 = wx.Panel(self.notebook_pane_3, wx.ID_ANY)
        self.panel_3 = wx.Panel(self.notebook_pane_3, wx.ID_ANY)
        self.panel_2 = wx.Panel(self.notebook_pane_3, wx.ID_ANY)
        self.button_1 = wx.Button(self.notebook_pane_3, wx.ID_ANY, u"选择模板")
        self.button_2 = wx.Button(self.notebook_pane_3, wx.ID_ANY, u"选择单文件")
        self.button_3 = wx.Button(self.notebook_pane_3, wx.ID_ANY, u"选择文件夹")
        self.panel_5 = wx.Panel(self.notebook_pane_3, wx.ID_ANY)
        self.button_4 = wx.Button(self.notebook_pane_3, wx.ID_ANY, u"开始COPY")
        self.panel_4 = wx.Panel(self.notebook_pane_3, wx.ID_ANY)

        self.Bind(wx.EVT_BUTTON, self.OnClick_1, self.button_14)
        self.Bind(wx.EVT_BUTTON, self.OnClick_2, self.button_15)
        self.Bind(wx.EVT_BUTTON, self.OnClick_3, self.button_16)
        self.Bind(wx.EVT_BUTTON, self.OnClick_4, self.button_17)
        self.Bind(wx.EVT_BUTTON, self.OnClick_5, self.button_1)
        self.Bind(wx.EVT_BUTTON, self.OnClick_6, self.button_2)
        self.Bind(wx.EVT_BUTTON, self.OnClick_7, self.button_3)
        self.Bind(wx.EVT_BUTTON, self.OnClick_8, self.button_4)
        self.Bind(wx.EVT_BUTTON, self.OnClick_9, self.button_5)
        self.Bind(wx.EVT_BUTTON, self.OnClick_10, self.button_6)
        self.Bind(wx.EVT_BUTTON, self.OnClick_11, self.button_7)


        self.combo_box_1.Bind(wx.EVT_COMBOBOX, self.OnCombo_1)
        self.combo_box_2.Bind(wx.EVT_COMBOBOX, self.OnCombo_2)
        self.combo_box_3.Bind(wx.EVT_COMBOBOX, self.OnCombo_3)
        self.combo_box_4.Bind(wx.EVT_COMBOBOX, self.OnCombo_4)

        self.combo_box_5.Bind(wx.EVT_COMBOBOX, self.OnCombo_5)

        self.checkbox_8.Bind(wx.EVT_CHECKBOX, self.OnCheck_1)
        self.checkbox_9.Bind(wx.EVT_CHECKBOX, self.OnCheck_2)
        self.checkbox_10.Bind(wx.EVT_CHECKBOX, self.OnCheck_3)

        self.__set_properties()
        self.__do_layout()
        # end wxGlade

    def OnCheck_1(self, event):
        global bl
        bl = self.checkbox_8.GetValue()


    def OnCheck_2(self, event):
        global It
        It = self.checkbox_9.GetValue()

    def OnCheck_3(self, event):
        global w2pdf
        w2pdf = self.checkbox_10.GetValue()

    def OnCombo_1(self, event):
        global font1
        font1 = self.combo_box_1.GetValue()

    def OnCombo_2(self, event):
        global font2
        font2 = (self.combo_box_2.GetValue())

    def OnCombo_3(self, event):

        global size1
        size1 = self.combo_box_3.GetValue()
        size1 = fontdir.fonts.sizeco(size1)

    def OnCombo_4(self, event):
        global size2
        size2 = self.combo_box_4.GetValue()
        size2 = fontdir.fonts.sizeco(size2)

    def OnCombo_5(self, event):
        global font3
        font3 = self.combo_box_5.GetValue()

    def OnClick_1(self, event):

        dlg = wx.FileDialog(self, message="", wildcard="*.doc|*.docx", style=wx.FD_OPEN)
        dlg.ShowModal()

        global open_file
        open_file = dlg.GetPath()
        self.information("选择文件完成")

    def OnClick_2(self, event):
        dlg = wx.DirDialog(self, u"选择文件夹", style=wx.DD_DEFAULT_STYLE)
        dlg.ShowModal()
        global open_dir
        open_dir = dlg.GetPath()
        global open_file
        open_file = None
        self.information("选择文件夹完成")

    def OnClick_3(self, event):

        if open_file == None and open_dir == None:

            self.information("先选择文件或文件夹")
        else:
            if open_dir != None:
                formate_dir(open_dir)

            if open_file != None:
                formate_doc(open_file)

            self.information("处理完毕")
            w.Quit

    def OnClick_4(self, event):
        wx.Exit()



    def OnClick_5(self,event):
        dlg = wx.FileDialog(self, message="", wildcard="*.doc|*.docx", style=wx.FD_OPEN)
        dlg.ShowModal()
        moban=convert_path(dlg.GetPath())

        global doc_moban

        doc_moban=w.Documents.Open(moban)
        self.information("模板选择完成")


    def OnClick_6(self, event):
        dlg = wx.FileDialog(self, message="", wildcard="*.doc|*.docx", style=wx.FD_OPEN)
        dlg.ShowModal()

        global open_file1
        open_file1 = dlg.GetPath()
        self.information("选择文件完成")

    def OnClick_7(self, event):

        dlg = wx.DirDialog(self, u"选择文件夹", style=wx.DD_DEFAULT_STYLE)
        dlg.ShowModal()
        global open_dir1
        open_dir1 = dlg.GetPath()
        global open_file1
        open_file1= None
        self.information("选择文件夹完成")



    def OnClick_8(self, event):
        if doc_moban==None:
            self.information("请选择模板")
        else:
            if open_file1 == None and open_dir1 == None:

                self.information("先选择文件或文件夹")
            else:
                
                if open_dir1 != None:
                    HF(open_dir1)


                if open_file1 != None:
                    
                    paste(open_file1)
                    doc_moban.Close()

                self.information("COPY完毕")
                w.Quit



    def OnClick_9(self, event):
        dlg = wx.FileDialog(self, message="", wildcard="*.doc|*.docx", style=wx.FD_OPEN)
        dlg.ShowModal()

        global open_file2
        open_file2 = dlg.GetPath()
        self.information("选择文件完成")

    def OnClick_10(self, event):
        dlg = wx.DirDialog(self, u"选择文件夹", style=wx.DD_DEFAULT_STYLE)
        dlg.ShowModal()
        global open_dir2
        open_dir2 = dlg.GetPath()
        global open_file2
        open_file2 = None
        self.information("选择文件夹完成")

    def OnClick_11(self, event):

        if open_file2 == None and open_dir2 == None:

            self.information("先选择文件或文件夹")
        else:
            if open_dir2 != None:

                doc2pdf_dir(open_dir2)

            if open_file2 != None:
                doc2pdf(open_file2)

            self.information("转换完毕")
            w.Quit

    # end wxGlade
    def information(self, message):
        dlg = wx.MessageDialog(None,  message,"Tips", wx.OK | wx.ICON_INFORMATION)
        dlg.ShowModal()

    def __set_properties(self):
        # begin wxGlade: MyFrame.__set_properties
        self.SetTitle("格式化文件批处理系统")
        self.button_14.SetMinSize((60, 30))
        self.button_15.SetMinSize((60, 30))
        self.button_16.SetMinSize((60, 30))
        self.button_17.SetMinSize((60, 30))
        # end wxGlade

    def __do_layout(self):
        # begin wxGlade: MyFrame.__do_layout
        sizer_1 = wx.BoxSizer(wx.VERTICAL)
        sizer_2 = wx.BoxSizer(wx.HORIZONTAL)
        grid_sizer_3 = wx.GridSizer(3, 3, 0, 0)
        grid_sizer_4 = wx.GridSizer(3, 3, 0, 0)
        grid_sizer_1 = wx.GridSizer(3, 4, 0, 0)
        sizer_9 = wx.BoxSizer(wx.HORIZONTAL)
        grid_sizer_2 = wx.GridSizer(2, 2, 0, 0)
        grid_sizer_1.Add(self.checkbox_8, 0, wx.ALIGN_CENTER | wx.EXPAND, 0)
        label_3 = wx.StaticText(self.notebook_pane_1, wx.ID_ANY, u"中文字体")
        grid_sizer_1.Add(label_3, 0, wx.ALIGN_CENTER, 0)
        grid_sizer_1.Add(self.combo_box_1, 0, wx.EXPAND, 0)
        grid_sizer_1.Add(self.combo_box_3, 0, wx.EXPAND, 0)
        grid_sizer_1.Add(self.checkbox_9, 0, wx.ALIGN_CENTER | wx.EXPAND, 0)
        label_4 = wx.StaticText(self.notebook_pane_1, wx.ID_ANY, u"标题字体")
        grid_sizer_1.Add(label_4, 0, wx.ALIGN_CENTER, 0)
        grid_sizer_1.Add(self.combo_box_2, 0, wx.EXPAND, 0)
        grid_sizer_1.Add(self.combo_box_4, 0, wx.EXPAND, 0)
        grid_sizer_1.Add(self.checkbox_10, 0, wx.ALIGN_CENTER | wx.EXPAND, 0)
        label_5 = wx.StaticText(self.notebook_pane_1, wx.ID_ANY, u"英文字体")
        grid_sizer_1.Add(label_5, 0, wx.ALIGN_CENTER, 0)
        grid_sizer_1.Add(self.combo_box_5, 0, wx.EXPAND, 0)
        grid_sizer_2.Add(self.button_14, 0, 0, 0)
        grid_sizer_2.Add(self.button_15, 0, 0, 0)
        grid_sizer_2.Add(self.button_16, 0, 0, 0)
        grid_sizer_2.Add(self.button_17, 0, 0, 0)
        sizer_9.Add(grid_sizer_2, 1, wx.EXPAND, 0)
        grid_sizer_1.Add(sizer_9, 1, wx.EXPAND, 0)
        self.notebook_pane_1.SetSizer(grid_sizer_1)
        grid_sizer_4.Add(self.panel_6, 1, wx.EXPAND, 0)
        grid_sizer_4.Add(self.panel_7, 1, wx.EXPAND, 0)
        grid_sizer_4.Add(self.panel_8, 1, wx.EXPAND, 0)
        grid_sizer_4.Add(self.button_5, 0, wx.ALIGN_CENTER, 0)
        grid_sizer_4.Add(self.button_6, 0, wx.ALIGN_CENTER, 0)
        grid_sizer_4.Add(self.button_7, 0, wx.ALIGN_CENTER, 0)
        grid_sizer_4.Add(self.panel_9, 1, wx.EXPAND, 0)
        grid_sizer_4.Add(self.panel_11, 1, wx.EXPAND, 0)
        grid_sizer_4.Add(self.panel_10, 1, wx.EXPAND, 0)
        self.notebook_pane_2.SetSizer(grid_sizer_4)
        grid_sizer_3.Add(self.panel_1, 1, wx.EXPAND, 0)
        grid_sizer_3.Add(self.panel_3, 1, wx.EXPAND, 0)
        grid_sizer_3.Add(self.panel_2, 1, wx.EXPAND, 0)
        grid_sizer_3.Add(self.button_1, 0, wx.ALIGN_CENTER, 0)
        grid_sizer_3.Add(self.button_2, 0, wx.ALIGN_CENTER, 0)
        grid_sizer_3.Add(self.button_3, 0, wx.ALIGN_CENTER, 0)
        grid_sizer_3.Add(self.panel_5, 1, wx.EXPAND, 0)
        grid_sizer_3.Add(self.button_4, 0, wx.ALIGN_CENTER, 0)
        grid_sizer_3.Add(self.panel_4, 1, wx.EXPAND, 0)
        sizer_2.Add(grid_sizer_3, 1, wx.EXPAND, 0)
        self.notebook_pane_3.SetSizer(sizer_2)
        self.notebook.AddPage(self.notebook_pane_1, u"格式化文件")
        self.notebook.AddPage(self.notebook_pane_2, u"转化PDF")
        self.notebook.AddPage(self.notebook_pane_3, u"替换页眉页脚")
        sizer_1.Add(self.notebook, 1, wx.EXPAND, 0)
        self.SetSizer(sizer_1)
        self.Layout()
        # end wxGlade

# end of class MyFrame


def replace_doc(self, string, new_string):
    '''替换文字'''
    self.Selection.Find.ClearFormatting()
    self.Selection.Find.Replacement.ClearFormatting()
    self.Selection.Find.Execute(string, False, False, True, False, False, True, 1, True, new_string, 2)


def replace_en(self):
    '''替换文字'''
    self.Selection.Find.ClearFormatting()
    self.Selection.Find.Replacement.Font.Name = font3
    self.Selection.Find.Replacement.Font.Italic = True
    self.Selection.Find.Execute('^$', False, False, False, False, False, True, 1, True, '^&', 2)


def formate_doc(filename1):
    filename2 = convert_path(filename1)

    doc = w.Documents.Open(FileName=filename2)
    doc.PageSetup.PaperSize = 7
    doc.PageSetup.Orientation = 0

    # 1.修改正文字体、字号
    w.ActiveDocument.Select()
    w.Selection.Paragraphs.LineSpacing = 18
    w.Selection.Font.Bold = bl
    w.Selection.Font.Name = font1
    w.Selection.Font.Name = font3
    w.Selection.Font.Size = size1  # 五号
    replace_doc(w, '.', '。')

    # 前两行清除格式,主要是首行缩进
    doc.Paragraphs(1).Range.Select()
    w.Selection.ClearFormatting()

    # 第一行改字体、字号、居中
    par1 = doc.Paragraphs(1).Range
    par1.ParagraphFormat.Reset()  # 取消首行缩进
    par1.Font.Name = font2
    par1.Font.Size = size2  # 三号
    par1.ParagraphFormat.Alignment = 1

    replace_en(w)  # 英文字符进行斜体替换

    if w2pdf == True:
        if filename2.endswith(".doc"):
            doc.SaveAs(filename2.replace(".doc", ".pdf"), FileFormat=17)
        else:
            doc.SaveAs(filename2.replace(".docx", ".pdf"), FileFormat=17)

    doc.Close()


def formate_dir(wenjianjia):
    for root, dirnames, filenames in os.walk(wenjianjia):
        for filename in filenames:
            if filename.endswith(".doc") or filename.endswith(".docx"):
                classRTF = os.path.join(root, filename)

                formate_doc(classRTF)


def paste(input_file):

        doc1 = w.Documents.Open(input_file)
        # copyheader()
        doc_moban.Sections[0].Headers[0].Range.Copy()
        doc1.Sections[0].Headers[0].Range.Paste()
        doc_moban.Sections[0].Footers[0].Range.Copy()
        # copyfooter()
        doc1.Sections[0].Footers[0].Range.Paste()

        doc1.Close()

def HF(input_dir):
    for root, dirnames, filenames in os.walk(input_dir):
        for filename in filenames:
            if filename.endswith(".doc") or filename.endswith(".docx"):
                classRTF = os.path.join(root, filename)

                paste(classRTF)

    doc_moban.Close()
    w.Quit


def doc2pdf(filename1):

    filename = convert_path(filename1)

    doc = w.Documents.Open(filename)
    if filename.endswith(".doc"):
        doc.SaveAs(filename.replace(".doc", ".pdf"), FileFormat=17)
    else:
        doc.SaveAs(filename.replace(".docx", ".pdf"), FileFormat=17)
    doc.Close()
    w.Quit()


def doc2pdf_dir(dir_name):
    for root, dirs, filenames in walk(dir_name):
        for filename in filenames:
            if filename.endswith(".doc") or filename.endswith(".docx"):
                classRTF = os.path.join(root, filename)
                doc2pdf(classRTF)


def convert_path(path: str) -> str:
    seps = r'\/'
    sep_other = seps.replace(os.sep, '')
    return path.replace(sep_other, os.sep) if sep_other in path else path
    # end wxGlade



class MyApp(wx.App):
    def OnInit(self):
        self.frame = MyFrame(None, wx.ID_ANY, "")
        self.SetTopWindow(self.frame)
        self.frame.Show()
        return True

# end of class MyApp

if __name__ == "__main__":
    app = MyApp(0)
    app.MainLoop()

把combobox的选项单做了一个class,后面方便更新

class fonts():

    fonts=["宋体","黑体","仿宋","楷体","华文细黑","华文新魏","华文隶书"]
    sizes=["八号","七号","小六","六号","小五","五号","小四","四号","小三","三号","小二","二号","小一","一号","小初","初号"]
    sizec=["5","5.5","6.5","7.5","9","10.5","12","14","15","16","18","22","24","26","36","42"]

    def sizeco(size1):
            conter=0
            for i in fonts.sizes:

                if i==size1:
                    return fonts.sizec[conter]
                conter+=1


小结

这个基本算是完成了,有一些地方觉得应该改进的,比如说UI和event应该分开写,这样后面回比较方便修改,不用提心吊胆不小心把哪里改错了😄