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