python提取word标题_用Python从MS-Word文档中提取标题
单词对象模型可以找到here。您的doc对象将包含这些属性,您可以使用它们执行所需的操作(请注意,我没有将此功能用于Word,因此我对对象模型的了解很少)。例如,如果要阅读文档中的所有单词,可以执行以下操作:for word in doc.Words:print word你会得到所有的单词。这些word项中的每一项都是Word对象(引用here),因此您可以在迭代期间访问这些属性。在您的情况下,以
单词对象模型可以找到here。您的doc对象将包含这些属性,您可以使用它们执行所需的操作(请注意,我没有将此功能用于Word,因此我对对象模型的了解很少)。例如,如果要阅读文档中的所有单词,可以执行以下操作:for word in doc.Words:
print word
你会得到所有的单词。这些word项中的每一项都是Word对象(引用here),因此您可以在迭代期间访问这些属性。在您的情况下,以下是如何获得风格:
^{pr2}$
在带有单个标题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']
魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。
更多推荐



所有评论(0)