python - 如何使用 python-pptx 从 powerpoint 中的组形状中的文本形状中提取文本。
问题描述
我的 PowerPoint 幻灯片有许多组形状,其中有子文本形状。
早些时候我使用了这段代码,但它不处理组形状。
for eachfile in files:
prs = Presentation(eachfile)
textrun=[]
for slide in prs.slides:
for shape in slide.shapes:
if hasattr(shape, "text"):
print(shape.text)
textrun.append(shape.text)
new_list=" ".join(textrun)
text_list.append(new_list)
我正在尝试从这些子文本框中提取文本。我已经设法使用 GroupShape.shape 到达这些子元素但我得到一个错误,这些是“属性”类型的,所以我无法访问文本或迭代(TypeError:“属性”对象不可迭代)他们。
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
。因此,您需要迭代组中的形状并从每个形状中获取文本。
请注意,此解决方案仅深入一层。递归方法可用于深度优先遍历树并从包含组的组中获取文本(如果有的话)。
另请注意,并非所有形状都有文本,因此您必须检查该.has_text_frame
属性以避免引发异常,例如图片形状。
推荐阅读
- java - Firebase电话身份验证在Android中不起作用
- postgresql - 当使用 pgloader 将数据从 mysql 迁移到 postgresql 时,显示通过 ECASE 表达式
- node.js - Passport.js 将 azure-ad 身份验证链接视为相对链接,尝试登录时返回 404
- ruby-on-rails - Ruby on Rails - 在 OSX 上使用 Ruby 2.4.4 而不是 rails 5.1.6 的配置问题/异常
- asp.net - ASP .Net MVC Web 应用程序搜索过滤器不起作用?
- html - jQuery 每个函数都不能用于将查询字符串附加到 URL
- c# - c#图表内存不足异常
- google-chrome - 来自 localhost 的文件可以用作 web_accessible_resources 吗?
- android - HMS Location Kit,位置更新仅在用户选择“始终允许”时有效
- python - 根据运行时计算的值动态创建复杂的嵌套 JSON