本站资源是站长搜集整理而成,版权均归原作者所有,若无意中侵犯到您的版权利益,请来信联系我们删除! 本站所有资源只用于研究学习,不得作为商业用途、非法谋取暴利,否则,一切后果均由自己承担!

首页 > 教程

word文档提取目录

  • slbcun
  • 2025-04-08
  • 1296 ℃

某提案汇总文档没有做目录,wps、word自带的功能也不能正确提取目录,就用python写了一个提取word文档目录的代码。
使用前需安装库:
pip install python-docx
修改了一下,用正则表达式来取提案号,避免取错
修改了二下,正则+开头来取提案号,且提案号数字最多三位,提高容错度

import re
from docx import Document
 
# 遍历文档中的段,取目录
def get_table_of_contents(doc):
    toc = []
    tmp=""
    i=0
    for paragraph in doc.paragraphs:
        match i:
            case 0:
                if re.search("第\\d{1,3}号", paragraph.text) and paragraph.text.startswith("第") and len(paragraph.text)<=5:
                   tmp=paragraph.text
                   i=1
            case 1:
                if paragraph.text.startswith("案    由:"):
                   toc.append(tmp+" "+paragraph.text.strip("案    由:"))
                   i=0
    return toc
 
# 打开Word文档
doc = Document("D:\\1.docx")
 
# 取目录
table_of_contents = get_table_of_contents(doc)
 
# 遍历打印目录
for para in table_of_contents:
    print(para)


文章评论 (0)

    • 这篇文章还没有收到评论,赶紧来抢沙发吧~


Top