You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

119 lines
3.5 KiB

from docx import Document
from docx.oxml import OxmlElement
from docx.oxml.ns import qn
from operator import eq
flag = True
def get_paragraph_shading(p):
"""
Get paragraph`s shading
Usage:
get_paragraph_shading(paragraph)
"""
p_pr = p._p.get_or_add_pPr() # 获取段落的pPr
# print(p_pr)
p_shd = p_pr.first_child_found_in("w:shd") # 找到 'w:shd' 标签
# 如果不存在,就创建
if p_shd is None:
p_shd = OxmlElement('w:shd')
p_pr.append(p_shd)
# 获取各属性的值
val = p_shd.get(qn('w:val'))
# color = p_shd.get(qn('w:color'))
fill = p_shd.get(qn('w:fill'))
print([val, fill])
return [val, fill]
def get_paragraph_boders(p):
"""
Get paragraph`s boders
Usage:
get_paragraph_boders(paragraph)
"""
p_pr = p._p.get_or_add_pPr() # 获取段落的pPr
p_borders = p_pr.first_child_found_in("w:pBdr") # 找到 'p_borders' 标签
# 如果不存在,就创建
if p_borders is None:
p_borders = OxmlElement('w:pBdr')
p_pr.append(p_borders)
# 获取各属性的值
borders = []
for edge in ('left', 'top', 'right', 'bottom'):
element = p_borders.find(qn('w:{}'.format(edge)))
if element is None:
element = OxmlElement('w:{}'.format(edge))
p_borders.append(element)
border = []
for key in ["sz", "val", "color"]:
temp = str(element.get(qn('w:{}'.format(key))))
if temp == 'none' or temp == '0' or temp == 'auto' or temp == 'NONE':
temp = 'None'
border.append(temp)
borders.append(border)
return borders
def get_text_borders(p):
t_pr = p.runs[0].element.rPr
t_bor = t_pr.first_child_found_in("w:bdr") # 找到 'w:bdr' 标签
# 如果不存在,就创建
if t_bor is None:
t_bor = OxmlElement('w:bdr')
t_pr.append(t_bor)
# # 获取各属性的值
val = t_bor.get(qn('w:val'))
color = t_bor.get(qn('w:color'))
sz = t_bor.get(qn('w:sz'))
return [val, sz, color]
def Comp(name1, name2):
"""
Compare the diferences of two files
Usage:
Comp(file_name1, file_name2)
"""
global flag
ff = 'K:/工作/traveler/test/'
# s = Document(name1)
# t = Document(name2)
s = Document(ff + name1)
t = Document(ff + name2)
# 获取段落
x = s.paragraphs
y = t.paragraphs
l = len(x)
for i in range(l-1):
s_shd = get_paragraph_shading(x[i])
t_shd = get_paragraph_shading(y[i])
s_border = get_paragraph_boders(x[i])
t_border = get_paragraph_boders(y[i])
if not eq(s_shd, t_shd):
print('效果对比出错,问题:',s_shd,'应该修改为:',t_shd)
print(1)
flag = False
break
if not eq(s_border, t_border):
print(1)
print('效果对比出错,问题:',s_border,'应该修改为:',t_border)
flag = False
break
# 判断标题的文字边框
if not eq(get_text_borders(x[0]), get_text_borders(y[0])):
print('文字边框设置出错,问题:',get_text_borders(x[0]),'应该修改为:',get_text_borders(y[0]))
flag = False
try:
Comp('中国共产党党史.docx', '美化文档.docx')
if flag:
print('Accepted!')
else:
print('文件内容错误,请调整后重试!')
except Exception as e:
print(e)
print('请按步骤创建、操作文本后重试!')