python-pptx 从幻灯片标题中提取文本

python-pptx Extract text from slide titles

我正在 python 中构建文档检索引擎,其中 returns 文档根据其与用户提交的查询的相关性进行排名。我有 collection 份文档,其中还包括 PowerPoint 文件。对于 PPT,我想在结果页面上向用户显示前几张幻灯片的标题,以提供 him/her 更清晰的图片(有点像我们在 Google 搜索中看到的)。

基本上,我想使用 python 从 PPT 文件中提取幻灯片标题中的文本。为此,我正在使用 python-pptx 包。目前我的实现看起来像这样

from pptx import Presentation
prs = Presentation(filepath) # load the ppt
slide_titles = [] # container foe slide titles
for slide in prs.slides: # iterate over each slide
        title_shape =  slide.shapes[0] # consider the zeroth indexed shape as the title
        if title_shape.has_text_frame: # is this shape has textframe attribute true then
            # check if the slide title already exists in the slide_title container
            if title_shape.text.strip(""" !@#$%^&*)(_-+=}{][:;<,>.?"'/<,""")+ '. ' not in slide_titles: 
                slide_titles.append(title_shape.text.strip(""" !@#$%^&*)(_-+=}{][:;<,>.?"'/<,""")+ '. ')  

但如您所见,我假设每张幻灯片上的零索引形状都是幻灯片标题,但显然并非每次都是如此。关于如何实现这一目标的任何想法?

提前致谢。

Slide.shapes (a SlideShapes object) 有 属性 .title 其中 returns 标题形状当有一个(通常是) 或 None 如果没有标题。
http://python-pptx.readthedocs.io/en/latest/api/shapes.html#slideshapes-objects

这是访问标题形状的首选方式。

请注意,并非所有幻灯片都有标题形状,因此您必须测试 None 结果以避免在这种情况下出现错误。

另请注意,用户有时会使用不同的标题形状,例如他们可能会添加一个单独的新文本框。因此,您不能保证获得作为幻灯片标题“出现”的文本。但是,您将获得与 PowerPoint 认为的标题相匹配的文本,例如,它在“大纲”视图中显示为该幻灯片标题的文本。

prs = Presentation(path)
for slide in prs.slides:
    title_shape = slide.title
    if title_shape is None:
        continue
    print(title_shape.text)

如何从目录中的 pptx 中提取所有文本(来自 this blog

from pptx import Presentation
import glob

for eachfile in glob.glob("*.pptx"):
    prs = Presentation(eachfile)
    print(eachfile)
    print("----------------------")
    for slide in prs.slides:
        for shape in slide.shapes:
            if hasattr(shape, "text"):
                print(shape.text)
local_pptxFileList = ["abc.pptx"]


for i in local_pptxFileList:
            ppt = Presentation(i)
            for slide in ppt.slides:
                for shape in slide.shapes:
                    if shape.has_text_frame:
                        print(shape.text)