我在目录中有很多要搜索的pptx文件,我正在这些文件中查找特定的单词“数据” 。我创建了下面的代码,该代码读取所有文件,但没有提供正确的结果 true或false 。例如,在qreader = QREader.Builder(view.context, surface_view, QRDataListener { data ->
myTextView.post {
doSomething(data)
}
})
.facing(QREader.BACK_CAM)
.enableAutofocus(true)
.height(surface_view.height)
.width(surface_view.width)
.build()
中,单词“数据” 以两个“形状” 存在。问题是确切的错误在哪里以及为什么代码会产生错误的结果。
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')))
预期结果将是在一张幻灯片中找到单词“ data”并打印true。实际上,预期结果将是:
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
如果在每张幻灯片的任何形状中均存在该单词,则为真;如果在幻灯片的所有形状中均不存在该单词,则为否。
答案 0 :(得分: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
答案 1 :(得分: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
要完全按照需要工作,需要以不同的方式处理中断(中断所有正在进行的循环)。这会使代码复杂一些,而错过了对组解析的关注,因此在此忽略。