在多个powerpoint文件Python中查找单词

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

我有很多pptx文件要在目录中搜索,我正在寻找这些文件中的特定单词“data”。我创建了下面的代码来读取所有文件,但它没有提供正确的结果true或false。例如,在Person1.pptx中,“数据”一词存在于两个“形状”中。问题是错误到底是什么以及为什么代码的结果不正确。

from pptx import Presentation
import os
files = [x for x in os.listdir("C:/Users/../Desktop/Test") if x.endswith(".pptx")]
for eachfile in files:
    prs = Presentation("C:/Users/.../Desktop/Test/" + eachfile)
    print(eachfile)
    print("----------------------")
    for slide in prs.slides:
        for shape in slide.shapes:
            print ("Exist? " + str(hasattr(shape, 'data')))

结果如下

Person1.pptx
----------------------
Exist? False
Exist? False
Exist? False
Exist? False
Exist? False
Exist? False
Exist? False
Exist? False
Person2.pptx
----------------------
Exist? False
Exist? False
Exist? False
Exist? False
Exist? False
Exist? False
Exist? False
Exist? False
Exist? False
Exist? False
Exist? False

预期的结果是在其中一个幻灯片中找到单词“data”并打印为true。实际上预期的结果是:

Person1.pptx
----------------------
Exist? True

Person1.pptx
----------------------
Exist? False

如果在每个幻灯片中的任何形状中存在该单词,则为真,如果在幻灯片的所有形状中该单词不存在,则为假。

python-3.x file text powerpoint extraction
2个回答
0
投票

我自己找到了。 :)

from pptx import Presentation
import os

files = [x for x in os.listdir("C:/Users/.../Desktop/Test") if x.endswith(".pptx")] 

for eachfile in files:
    prs = Presentation("C:/Users/.../Desktop/Test/" + eachfile) 
    for slide in prs.slides:
        for shape in slide.shapes:
            if hasattr(shape, "text"):
                shape.text = shape.text.lower()
                if "whatever_you_are_looking_for" in shape.text:
                    print(eachfile)
                    print("----------------------")
                    break

0
投票

回答这个问题,因为上述答案可能比我误导。它不完整。这既没有错。但在许多现实生活中,它会产生错误的结果。

问题在于它忽略了有许多结构要解析。上面的代码只解析其中的一些(直接在文本中使用文本的形状)。最需要解析的最重要的结构是找到所有需要文本的形状,是组。这是一种形状,其本身可能不包含文本,但可能包含包含文本的形状。

此外,该组形状或其形状可以依次包含其他组。这导致我们需要迭代搜索策略。因此,在解析每张幻灯片中的形状时需要不同的方法。最好通过重用上面的代码来显示,保留第一部分:

from pptx import Presentation
import os

files = [x for x in os.listdir("C:/Users/.../Desktop/Test") if x.endswith(".pptx")] 

for eachfile in files:
    prs = Presentation("C:/Users/.../Desktop/Test/" + eachfile) 
    for slide in prs.slides:

然后我们需要用递归部分的调用替换“hasattr”测试:

        checkrecursivelyfortext(slide.shapes)

并且还插入函数的新递归函数定义(如在import语句之后)。为了使比较更容易,插入的函数使用与上面相同的代码,只添加递归部分:

def checkrecursivelyfortext(shpthissetofshapes):
    for shape in shpthissetofshapes:
        if shape.shape_type == MSO_SHAPE_TYPE.GROUP:
            checkrecursivelyfortext(shape.shapes)
        else:
            if hasattr(shape, "text"):
                shape.text = shape.text.lower()
                if "whatever_you_are_looking_for" in shape.text:
                    print(eachfile)
                    print("----------------------")
                    break

为了完全按照需要工作,需要以不同的方式处理中断(打破所有正在进行的循环)。这会使代码复杂化并忽略对组解析的关注,因此忽略了这一点。

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