python处理word

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()

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值