![](/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.