Word 对象模型可以在here 找到。您的doc 对象将包含这些属性,您可以使用它们来执行所需的操作(请注意,我没有在 Word 中使用此功能,因此我对对象模型的了解很少)。例如,如果您想阅读文档中的所有单词,您可以这样做:
for word in doc.Words:
print word
你会得到所有的单词。每个word 项都是Word 对象(参考here),因此您可以在迭代期间访问这些属性。就您而言,这是获得样式的方式:
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。正如下面代码 cmets 中所解释的,您需要引用对象本身的 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']