import win32com.client as win32
word = win32.Dispatch("Word.Application")
word.Visible = 0
word.Documents.Open("MyDocument")
doc = word.ActiveDocument
我如何知道单词对象的所有功能?我在帮助文档中找不到任何有用的东西。
答案 0 :(得分:3)
可以找到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
。如下面的代码注释中所述,您需要引用对象本身的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']
答案 1 :(得分:2)
您还可以使用Google Drive SDK将Word文档转换为更有用的内容,例如HTML,您可以轻松地提取标题。
答案 2 :(得分:1)
将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)