LoginSignup
1
1

python-pptxによる代替テキストへのアクセス

Posted at

代替テキスト機能とは

Microsoft Officeソフトウェアにおいて、各種オブジェクトに説明をつけるための機能です。
資料の読み上げ時に画像を説明するために利用されるそうです。
image.png

python-pptxで代替テキストにアクセスするには

最新版のpython-pptxでは代替テキストへのアクセス機能が実装されていません。
最新版は2021年9月にリリースされたもので、今後のアップデートも期待薄でしょう。

ただしインストール済みのpython-pptxを改変することで実装出来ます。
具体的な方法は下記のURLに則り、setterも実装しました。
https://github.com/scanny/python-pptx/pull/512/files

まずはpython-pptxのインストール先を調べましょう。

import pptx
print(pptx.__file__)    # C:\Users\..(中略)..\pptx\__init__.py

表示された__init__.pyが存在するpptxフォルダを開き、
oxml/shapes/shared.pyに下記の記述を追加します。

oxml/shapes/shared.py (170行目付近)
    @property
    def txBody(self):
        """
        Child ``<p:txBody>`` element, None if not present
        """
        return self.find(qn("p:txBody"))

+   @property
+   def shape_alt_text(self):
+       return self._nvXxPr.cNvPr.descr
+
+   @shape_alt_text.setter
+   def shape_alt_text(self, new_alt_text):
+       self._nvXxPr.cNvPr.descr = str(new_alt_text)

    @property
    def x(self):
        return self._get_xfrm_attr("x")
oxml/shapes/shared.py (315行目付近)
    name = RequiredAttribute("name", XsdString)
+   descr = OptionalAttribute('descr', XsdString)
    del _tag_seq

つづいてpptxフォルダに戻り、shapes/base.pyに下の記述を追加します。

shapes/base.py (135行目付近)
    @name.setter
    def name(self, value):
        self._element._nvXxPr.cNvPr.name = value

+   @property
+   def alt_text(self):
+       return self._element.shape_alt_text
+
+   @alt_text.setter
+   def alt_text(self, new_alt_text):
+       self._element.shape_alt_text = new_alt_text

    @property
    def part(self):

これで準備は完了です。

動作確認例

最初のスライドに画像(図形でも可)を1つ貼り付け、適当に代替テキストを設定してSample.pptxという名前で保存しました。
image.png

この代替テキストを表示した上で、変更して別ファイルとして保存するサンプルです。

from pptx import  Presentation

prs = Presentation('./Sample.pptx')
print(prs.slides[0].shapes[0].alt_text)    # '悩めるアザラシ'
prs.slides[0].shapes[0].alt_text = '実は眠いだけ'
prs.save('Modified.pptx')

image.png

問題なく表示・変更できることが確認されました。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1