我有一个 MS Word 文档包含一些文本和标题,我想提取标题,我安装了 Python for win32,但我不知道使用哪种方法,似乎 python for windows 的帮助文档没有列出功能的词对象。以下面的代码为例
import win32com.client as win32
word = win32.Dispatch("Word.Application")
word.Visible = 0
word.Documents.Open("MyDocument")
doc = word.ActiveDocument
Run Code Online (Sandbox Code Playgroud)
我怎么知道word对象的所有功能?我在帮助文档中没有找到任何有用的东西。
Word 对象模型可以在此处找到。您的doc对象将包含这些属性,您可以使用它们来执行所需的操作(请注意,我没有在 Word 中使用此功能,因此我对对象模型的了解很少)。例如,如果您想阅读文档中的所有单词,您可以这样做:
for word in doc.Words:
print word
Run Code Online (Sandbox Code Playgroud)
你会得到所有的单词。这些word项目中的每一个都将是一个Word对象(参考此处),因此您可以在迭代期间访问这些属性。对于您的情况,您可以通过以下方式获得样式:
for word in doc.Words:
print word.Style
Run Code Online (Sandbox Code Playgroud)
在具有单个标题 1 和普通文本的示例文档上,将打印:
Heading 1
Heading 1
Heading 1
Heading 1
Heading 1
Normal
Normal
Normal
Normal
Normal
Run Code Online (Sandbox Code Playgroud)
要将标题分组在一起,您可以使用itertools.groupby. 正如下面的代码注释中所解释的,您需要引用str()对象本身的 ,因为 usingword.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)
Run Code Online (Sandbox Code Playgroud)
这输出:
Heading 1 Here is some text
Normal
No header
Run Code Online (Sandbox Code Playgroud)
如果用列表理解替换join,您将得到以下内容(您可以在其中看到换行符):
Heading 1 ['Here ', 'is ', 'some ', 'text', '\r']
Normal ['\r', 'No ', 'header', '\r', '\r']
Run Code Online (Sandbox Code Playgroud)