实现功能:
version2:
将一篇word文档的各级标题内容分类,批量修改为自己想要的不同格式(包括字体、字号、位置、颜色、加粗、下划线等)
准备工作:
一篇word文档,python-docx库
效果展示:
代码:
from docx import Document
import docx
from docx.shared import Pt
from docx.shared import RGBColor
from docx.oxml.ns import qn
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
import re
data = docx.Document('1.docx')
data_change = Document()
user_style1 = data_change.styles.add_style('user_style1', 1)
user_style1.font.size = Pt(14)
user_style1.font.bold = True
user_style1.font.color.rgb = RGBColor(0x00, 0x00, 0x00)
user_style1.paragraph_format.alignment = WD_PARAGRAPH_ALIGNMENT.LEFT
user_style1.font.name = '黑体'
user_style1._element.rPr.rFonts.set(qn('w:eastAsia'), '黑体')
user_style2 = data_change.styles.add_style('user_style2', 1)
user_style2.font.size = Pt(12)
user_style2.font.bold = True
user_style2.font.color.rgb = RGBColor(0x00, 0x00, 0x00)
user_style2.paragraph_format.alignment = WD_PARAGRAPH_ALIGNMENT.LEFT
user_style2.font.name = '黑体'
user_style2._element.rPr.rFonts.set(qn('w:eastAsia'), '黑体')
user_style3 = data_change.styles.add_style('user_style3', 1)
user_style3.font.size = Pt(12)
user_style3.font.bold = True
user_style3.font.color.rgb = RGBColor(0x00, 0x00, 0x00)
user_style3.paragraph_format.alignment = WD_PARAGRAPH_ALIGNMENT.LEFT
user_style3.font.name = '宋体'
user_style3._element.rPr.rFonts.set(qn('w:eastAsia'), '宋体')
def change_ap_01(title):
data_change.add_paragraph(text = title,style = user_style1)
def change_ap_02(title):
data_change.add_paragraph(text = title,style = user_style2)
def change_ap_03(title):
data_change.add_paragraph(text = title,style = user_style3)
def find_numbers(pat):
s= pat
f2=re.findall('(\d+)',s)
f1 = len(f2)
return f1
l = len(data.paragraphs)
print(l)
for n in range(0,l):
element = data.paragraphs[n].text
if find_numbers(element) == 1:
change_ap_01(element)
elif find_numbers(element) == 2:
change_ap_02(element)
elif find_numbers(element) == 3:
change_ap_03(element)
else:
continue
data_change.save('changed.docx')