python -m pip install pypiwin32
pip install python-docx
"""shandiaomulufengzhuang.py"""
"""删除目录另存只留章节内容"""
import win32com.client as win32
from win32com.client import constants
import os
# 源文件路径
file_path = r'C:/Users/lulu/Desktop/梁啸叫我干啥/分章节/hp/aaa1.docx'
#第一章题目
diyizhangtimu = "哈利波特与阿兹卡班的囚徒 : 第1章 猫头鹰邮递"
#删掉的目录保存位置
mulu_path = 'C:/Users/lulu/Desktop/梁啸叫我干啥/分章节/hp/mulu.docx'
def shanmulu(file_path,diyizhangtimu,mulu_path):
word = win32.gencache.EnsureDispatch('Word.Application')
word.Visible = 0
# 打开
doc = word.Documents.Open(file_path)
# 光标start的查找
start = 0
print(start)
# 光标end的查找 同上
search_range = doc.Content
search_range.Find.Execute(FindText=diyizhangtimu)
search_range.Select()
word.Selection.MoveLeft()
end = word.Selection.Start.numerator
print(end)
# 选取光标start到光标end的内容
doc.Range(start, end).Select()
# 目录部分另存为
word.Selection.Copy()
mulu = word.Documents.Add()
mulu.Application.ActiveDocument.Range().Paste()
# 选取光标start到光标end的内容
doc.Range(start, end).Select()
# 删除目录部分仅留章节内容
word.Selection.Delete()
# 保存关闭文件
mulu.SaveAs(mulu_path) # 另存为
mulu.Close()
doc.Save()
doc.Close()
shanmulu(file_path,diyizhangtimu,mulu_path)
"""jiexuanyizhang.py"""
"""节选一章另存为"""
import win32com.client as win32
from win32com.client import constants
import os
# 源文件路径
file_path = r'C:/Users/lulu/Desktop/梁啸叫我干啥/分章节/hp/aaa1.docx'
#开始位置
tou = "哈利波特与阿兹卡班的囚徒 : 第1章 猫头鹰邮递"
#结束位置
wei = "哈利波特与阿兹卡班的囚徒 : 第2章 玛姬姑妈的大错误"
word = win32.gencache.EnsureDispatch('Word.Application')
word.Visible = 0
# 打开
doc = word.Documents.Open(file_path)
# 光标start的查找
search_range = doc.Content
search_range.Find.Execute(FindText=tou)
search_range.Select()
word.Selection.MoveLeft()
# 将光标位置赋予start
start = word.Selection.Start.numerator
print(start)
# 光标end的查找
search_range = doc.Content
search_range.Find.Execute(FindText=wei)
search_range.Select()
word.Selection.MoveLeft()
end = word.Selection.Start.numerator
print(end)
# 选取光标start到光标end的内容
doc.Range(start, end).Select()
# 复制
word.Selection.Copy()
# 粘贴的目标文件
doc_new = word.Documents.Add() # 创建新的word文档
# 粘贴
doc_new.Application.ActiveDocument.Range().Paste()
# 关闭两个文件
doc_new.SaveAs('C:/Users/lulu/Desktop/梁啸叫我干啥/分章节/hp/p1.docx') # 另存为
doc_new.Close()
doc.Close()