![](/img/trans.png)
[英]How to extract image from table in MS Word document with docx library?
[英]Extract headings from a MS Word document in Python
我有一個MS Word文檔包含一些文字和標題,我想提取標題,我為win32安裝了Python,但我不知道使用哪種方法,似乎python for windows的幫助文件沒有列出函數obejct這個詞。 以下面的代碼為例
import win32com.client as win32
word = win32.Dispatch("Word.Application")
word.Visible = 0
word.Documents.Open("MyDocument")
doc = word.ActiveDocument
我如何知道單詞對象的所有功能?我在幫助文檔中找不到任何有用的東西。
Word對象模型可以在這里找到。 您的doc
對象將包含這些屬性,您可以使用它們來執行所需的操作(請注意,我沒有將此功能與Word一起使用,因此我對對象模型的了解很少)。 例如,如果您想閱讀文檔中的所有單詞,您可以執行以下操作:
for word in doc.Words:
print word
你會得到所有的話。 每個word
項都是一個Word
對象( 這里引用),因此您可以在迭代期間訪問這些屬性。 在你的情況下,這是你如何獲得風格:
for word in doc.Words:
print word.Style
在具有單個標題1和普通文本的示例文檔上,將打印:
Heading 1
Heading 1
Heading 1
Heading 1
Heading 1
Normal
Normal
Normal
Normal
Normal
要將標題組合在一起,可以使用itertools.groupby
。 正如下面的代碼注釋中所解釋的,您需要引用對象本身的str()
,因為使用word.Style
返回一個實例,該實例無法與相同樣式的其他實例正確分組:
from itertools import groupby
import win32com.client as win32
# All the same as yours
word = win32.Dispatch("Word.Application")
word.Visible = 0
word.Documents.Open("testdoc.doc")
doc = word.ActiveDocument
# Here we use itertools.groupby (without sorting anything) to
# find groups of words that share the same heading (note it picks
# up newlines). The tricky/confusing thing here is that you can't
# just group on the Style itself - you have to group on the str().
# There was some other interesting behavior, but I have zero
# experience with COMObjects so I'll leave it there :)
# All of these comments for two lines of code :)
for heading, grp_wrds in groupby(doc.Words, key=lambda x: str(x.Style)):
print heading, ''.join(str(word) for word in grp_wrds)
這輸出:
Heading 1 Here is some text
Normal
No header
如果用列表推導替換join
,則得到以下內容(您可以在其中看到換行符):
Heading 1 ['Here ', 'is ', 'some ', 'text', '\r']
Normal ['\r', 'No ', 'header', '\r', '\r']
您還可以使用Google Drive SDK將Word文檔轉換為更有用的內容,例如HTML,您可以輕松地提取標題。
將word轉換為docx並使用python docx模塊
from docx import Document
file = 'test.docx'
document = Document(file)
for paragraph in document.paragraphs:
if paragraph.style.name == 'Heading 1':
print(paragraph.text)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.