5

MS Word ドキュメントにいくつかのテキストと見出しが含まれています。見出しを抽出したいのですが、win32 用の Python をインストールしましたが、使用する方法がわかりませんでした。Windows 用の python のヘルプ ドキュメントには関数がリストされていないようです。単語オブジェクトの。次のコードを例に取ります

import win32com.client as win32
word = win32.Dispatch("Word.Application")
word.Visible = 0
word.Documents.Open("MyDocument")
doc = word.ActiveDocument

ワード オブジェクトのすべての機能を知るにはどうすればよいですか?ヘルプ ドキュメントに役立つ情報が見つかりません。

4

3 に答える 3

4

Word オブジェクト モデルは、ここにあります。オブジェクトdocにはこれらのプロパティが含まれ、それらを使用して目的のアクションを実行できます (この機能を Word で使用したことがないため、オブジェクト モデルに関する知識が乏しいことに注意してください)。たとえば、ドキュメント内のすべての単語を読みたい場合は、次のようにします。

for word in doc.Words:
    print word

そして、あなたはすべての言葉を手に入れるでしょう。これらの各word項目はWordオブジェクト (ここを参照) になるため、反復中にこれらのプロパティにアクセスできます。あなたの場合、スタイルを取得する方法は次のとおりです。

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()using が返すため、オブジェクト自体のを参照する必要があります。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']
于 2013-01-09T15:06:44.567 に答える
3

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)
于 2018-02-22T10:37:03.070 に答える
2

また、Google ドライブ SDK を使用して、Word ドキュメントを HTML などのより便利なものに変換し、ヘッダーを簡単に抽出することもできます。

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

于 2013-01-09T14:59:31.990 に答える