【问题标题】:Extract headings from a MS Word document in Python在 Python 中从 MS Word 文档中提取标题
【发布时间】:2018-02-22 18:37:03
【问题描述】:

我有一个MS Word文档包含一些文本和标题,我想提取标题,我安装了python for win32,但是我不知道使用哪种方法,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 object的所有功能?我在帮助文档中没有找到任何有用的东西。

【问题讨论】:

  • 您正在访问 Word 的 win32com API,它不是 Python 的一部分,因此在 Python 中将没有它的文档。
  • 谢谢,那么如何找到COM API的文档,或者有什么方法可以列出COM对象的所有功能?
  • RocketDonkey 在his/her answer 中链接到它。
  • @Lattyware Ha,猜猜这是一个模棱两可的名字('his')。
  • @RocketDonkey 我确实很快检查了你的个人资料以寻找线索。我认为这比仅仅假设要好 XD

标签: python ms-word


【解决方案1】:

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']

【讨论】:

  • 好吧,这将打印多次标题,因为标题可能包含很多单词。
  • @zdd 是的,这更像是一个概念证明:) 我会用一种可能的方式将它们组合在一起,但绝对不能声称它是“公认的”win32 方式。
  • @zdd 添加了一个更新,希望对您有所帮助(绝对是一个有趣的 API :))。
【解决方案2】:

将 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)

【讨论】:

    【解决方案3】:

    您还可以使用 Google Drive SDK 将 Word 文档转换为更有用的内容,例如 HTML,您可以在其中轻松提取标题。

    https://developers.google.com/drive/manage-uploads

    【讨论】:

    • 作为另一种选择,我认为您也可以使用win32com将文档保存为html,然后提取标题。
    猜你喜欢
    • 2010-09-21
    • 2010-09-12
    • 1970-01-01
    • 2011-05-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-06
    • 2021-05-26
    相关资源
    最近更新 更多