[Python] 纯文本查看 复制代码from docx import Document
for i in range(1,14):
# 输入Word文档路径
input_docx = f'D:/52pj/fengzhang/老杨.458条人性秘术{str(i).zfill(2)}.docx'
for j in range(1,100):
# 输出Word文档路径
output_docx = f'D:/52pj/fengzhang/fengzhangjie/老杨.458条人性秘术{str(i).zfill(2)}{str(j).zfill(2)}.docx'
len1 = len(str(j))+1
len2 = len(str(j+1))+1
# 加载Word文档
doc = Document(input_docx)
# 标记是否已找到“第二章”或“第三章”
found_chapter_two = False
found_chapter_three = False
# 用于存储要保留的段落
paragraphs_to_keep = []
# 遍历文档中的段落
for paragraph in doc.paragraphs:
# 检查段首三个字符是否是“第二章”或“第三章”
if paragraph.text[:len1] == f'{str(j)}:':
found_chapter_two = True
paragraphs_to_keep.append(paragraph)
elif paragraph.text[:len2] == f'{str(j+1)}:':
found_chapter_three = True
break # 找到“第三章”后停止遍历
elif found_chapter_two:
# 如果已经找到了“第二章”,则保留当前段落及以后的段落
paragraphs_to_keep.append(paragraph)
# 如果找到“第三章”,则只保留到“第二章”的内容
# if found_chapter_three:
# paragraphs_to_keep = paragraphs_to_keep[:1] # 只保留第一个段落(通常是“第二章”本身)
# 创建一个新的Word文档,并添加要保留的段落
new_doc = Document()
if paragraphs_to_keep:
for paragraph in paragraphs_to_keep:
new_doc.add_paragraph(paragraph.text, style=paragraph.style)
# 保存新的Word文档
new_doc.save(output_docx)
print(f"处理完成,修改后的内容已保存到 {output_docx}")