from pptx.shapes.group import GroupShape
from pptx import Presentation
for eachfile in files:
prs = Presentation(eachfile)
textrun=[]
for slide in prs.slides:
for shape in slide.shapes:
for text in GroupShape.shapes:
print(text)
然后,我想捕获文本并将其附加到字符串中以进行进一步处理。
我的问题是,如何访问儿童文本元素并从中提取文本。我花了很多时间去文档和源代码,但无法弄清楚。任何帮助将不胜感激。
我认为您需要这样的东西:
from pptx.enum.shapes import MSO_SHAPE_TYPE
for slide in prs.slides:
# ---only operate on group shapes---
group_shapes = [
shp for shp in slide.shapes
if shp.shape_type == MSO_SHAPE_TYPE.GROUP
]
for group_shape in group_shapes:
for shape in group_shape.shapes:
if shape.has_text_frame:
print(shape.text)
一个组形状包含其他形状,可在
.shapes
.text
注意,该解决方案只会深入一个水平。递归方法可以用来漫步树的深度优先,并从包含组的组中获取文本。
也请注意,并非所有形状都有文本,因此您必须检查the there therce there thepripation。先前的答案仅解析其中一些(降至第二层形状)。但是,即使该层组形状也可能又包含更多的组。因此,我们需要迭代搜索策略。最好通过重复使用上述代码,保留第一部分:
.has_text_frame
然后我们需要替换“在groupShape.shape中的文本”:呼叫递归部分的测试:
from pptx.shapes.group import GroupShape
from pptx import Presentation
for eachfile in files:
prs = Presentation(eachfile)
textrun=[]
for slide in prs.slides:
for shape in slide.shapes:
还插入了该功能的新递归功能定义(例如导入语句之后)。为了使比较更轻松,插入的函数使用与上述相同的代码,仅添加递归部分: textrun=checkrecursivelyfortext(slide.shapes,textrun)
themmats bengtsson的答案是斑点上的
错误在这里:
def checkrecursivelyfortext(shpthissetofshapes,textrun):
for shape in shpthissetofshapes:
if shape.shape_type == MSO_SHAPE_TYPE.GROUP:
textrun=checkrecursivelyfortext(shape.shapes,textrun)
else:
if hasattr(shape, "text"):
print(shape.text)
textrun.append(shape.text)
return textrun
对于可读性,我将发布整个固定片段。
for slide in prs.slides:
for shape in slide.shapes:
textrun = checkrecursivelyfortext(slide.shapes,textrun)