You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python处理Visio组合形状及提取Documents文本

解决Visio组合形状中文本提取问题

以下是针对需求的示例代码,包含三个核心功能的实现:

1. 判断形状是否为组合形状

通过Shape对象的Type属性判断,当属性值为2(对应Visio的visTypeGroup常量)时,该形状为组合形状。

2. 判断组合形状中是否包含Documents形状

遍历组合形状的Shapes子集合,检查每个子形状的名称或主控形状名称是否为"Documents"。

3. 提取组合形状内Documents形状的文本

找到目标子形状后,直接读取其Text属性即可。

完整代码示例

import win32com.client

appVisio = win32com.client.Dispatch("Visio.Application")
vdoc = appVisio.Documents.Open(visiofile)

pagecount = vdoc.Pages.Count
with open(outputfile, 'w', encoding='utf-8') as fp:
    for p in range(pagecount):
        shps = vdoc.Pages(p+1).Shapes
        for shp in shps:
            # 打印当前形状的名称和文本
            print(shp.Name, shp.Text)
            fp.write(f"{shp.Name}: {shp.Text}\n")
            
            # 判断是否为组合形状
            if shp.Type == 2:  # visTypeGroup = 2
                print(f"形状 {shp.Name} 是组合形状")
                # 遍历组合内的子形状
                for sub_shp in shp.Shapes:
                    # 判断是否包含Documents形状
                    if sub_shp.Name == "Documents" or (hasattr(sub_shp, 'Master') and sub_shp.Master.Name == "Documents"):
                        doc_text = sub_shp.Text
                        print(f"组合 {shp.Name} 中找到Documents形状,文本为: {doc_text}")
                        fp.write(f"组合 {shp.Name} 内Documents文本: {doc_text}\n")

说明

  • 用shp.Type == 2直接判定组合形状,这是Visio对象模型中组合形状的固定类型标识。
  • 同时检查子形状名称和主控形状名称,避免因形状重命名导致匹配失败。
  • 写入文件时指定encoding='utf-8',防止中文文本乱码。

内容的提问来源于stack exchange,提问作者user19630212

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 04:24:13