word文档提取目录

25-04-08     slbcun     921℃     0

某提案汇总文档没有做目录,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条评论
  • 这篇文章还没有收到评论,赶紧来抢沙发吧~