无法使用Python-pptx删除PowerPoint幻灯片

问题描述 投票:0回答:4

我正在尝试使用 Python-pptx 删除包含特定关键字的 PowerPoint 幻灯片。如果关键字出现在幻灯片中的任何位置,则该幻灯片将被删除。我的代码如下:

from pptx import Presentation

String = 'Macro'

ppt = Presentation('D:\\Shaon\\pptss\\Regional.pptx')

for slide in ppt.slides:
    for shape in slide.shapes:
        if shape.has_text_frame:
            shape.text = String
            slide.delete(slide)

ppt.save('BODd.pptx')

执行后我收到内存错误。不知道如何解决这个问题。如何删除使用某些特定关键字的PPT幻灯片?

python python-3.x powerpoint python-pptx
4个回答
3
投票

可以使用以下代码删除整个幻灯片。因此,只需在生成幻灯片之前使用此功能即可获得干净且空的 PowerPoint 文件。通过更改索引,您还可以删除特定的幻灯片。

import os
import pptx.util
from pptx import Presentation

cwd = os.getcwd()
prs = Presentation(cwd + '\\ppt.pptx')
for i in range(len(prs.slides)-1, -1, -1): 
    rId = prs.slides._sldIdLst[i].rId
    prs.part.drop_rel(rId)
    del prs.slides._sldIdLst[i]

1
投票

您可以使用 pptx 库通过以下代码删除具有特定索引值的幻灯片:

from pptx import Presentation
#  create slides ------
presentation = Presentation('new.pptx') 

xml_slides = presentation.slides._sldIdLst  
slides = list(xml_slides)
xml_slides.remove(slides[index]) 

因此,要删除第一张幻灯片,

index
将为 0。


0
投票

我试图删除所有幻灯片,但从一个 pptx 文件中删除封面以重用布局,我得到的最佳解决方案是循环 Ferhat 的答案。

成功了:)

# Ferhat´s showed us how to list the slides:

xml_slides = prs.slides._sldIdLst  
slides = list(xml_slides)

# Then I loop for all except the first (index 0):

for index in range(1,len(slides)):
    xml_slides.remove(slides[index])


0
投票
for i in range(0,6,1):
        delete_slides(prs, 0)

def delete_slides(presentation, index):
        xml_slides = presentation.slides._sldIdLst  
        slides = list(xml_slides)
        xml_slides.remove(slides[index])

这是代码,您可以使用它从 0 索引中删除幻灯片。正如你所看到的,有一个范围,通过使用for循环,你可以设置要删除的页数。另外,如果您要从末尾删除页面,只需使用 -1。

像这样:

for i in range(0,6,1):
        delete_slides(prs, -1)

def delete_slides(presentation, index):
        xml_slides = presentation.slides._sldIdLst  
        slides = list(xml_slides)
        xml_slides.remove(slides[index])

希望对您有帮助。

© www.soinside.com 2019 - 2024. All rights reserved.