簡體   English   中英

如何使用python獲取word文檔中的所有書簽?

[英]How to get all bookmarks in the word document using python?

我需要提取“.docx”ms-word 文件中的所有書簽,但我發現的代碼無法正常工作。

from win32com import client
app=client.Dispatch('Word.Application')#Start independent process
app.Visible=True #Whether the setting is visible, if it is false, it will run in the background
word=app.Documents.Open(os.path.abspath('Word document path')) #Open word document
bookmarks=word.BookMarks #Get all bookmarks

我找到代碼的站點: https://www.programmersought.com/article/42847366218/

書簽變量的返回值是: <COMObject <unknown> 我希望所有的書簽都以文本格式出現,這樣我就可以以任何我想要的方式歸檔它們。

有什么幫助嗎?

我在另一個 stackoverflow 問題中找到了答案: 問題

所以 function 是:

def get_bookmarks(document):
    doc_element = document.part._element
    bookmarks_list = doc_element.findall('.//' + qn('w:bookmarkStart'))
    bookmarks_text = []

    for bookmark in bookmarks_list:
        par = bookmark.getparent()
        runs = par.findall(qn('w:r'))
        for run in runs:
            try:
                bookmarks_text.append(run.find(qn('w:t')).text)
            except Exception as e:
                print(e)

    return bookmarks_text

它正在使用 docx(python 模塊安裝

文檔是 docx.Document('path_example.docx')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM