如何从DOT/Graphviz图中按边权重提取占比前X%的边
DOT图前X%权重边提取实现方案
目前没有现成的Python第三方函数直接提供该功能,你可以基于pydot库解析DOT文件,自定义逻辑完成提取,具体实现如下:
前置依赖安装
pip install pydot
实现逻辑
- 用pydot读取解析DOT文件,获取所有边对象
- 提取每条边的
label属性,过滤掉无有效label的边,提取其中的数值作为权重(适配带单位的场景如示例中的10s) - 所有边按权重降序排序
- 按输入的占比计算需要提取的边数量,取排序后靠前的对应数量的边
- 可按需将提取的边导出为新的DOT文件
完整代码示例
import pydot import re from math import ceil def extract_top_x_percent_edges(dot_file_path, x_percent): # 解析DOT文件 graphs = pydot.graph_from_dot_file(dot_file_path) origin_graph = graphs[0] all_edges = origin_graph.get_edges() edge_weight_list = [] for edge in all_edges: label = edge.get_label() # 过滤无label的边 if not label: continue # 提取label中的数字部分作为权重,支持带单位的场景,如"10s""3.5ms" num_match = re.search(r"(\d+\.?\d*)", label.strip('"')) if not num_match: continue weight = float(num_match.group(1)) edge_weight_list.append((weight, edge)) # 按权重从高到低排序 edge_weight_list.sort(reverse=True, key=lambda x:x[0]) total_valid_edge = len(edge_weight_list) if total_valid_edge == 0: return origin_graph, [] # 计算需要提取的边数量 take_num = ceil(total_valid_edge * x_percent / 100) # 取前X%的边 top_edges = [item[1] for item in edge_weight_list[:take_num]] return origin_graph, top_edges # 调用示例 if __name__ == "__main__": # 提取test.dot文件中权重前20%的边 origin_graph, top_edges = extract_top_x_percent_edges("test.dot", 20) # 如需将提取的边导出为新的DOT文件 new_graph = pydot.Dot(graph_type=origin_graph.get_type()) for edge in top_edges: new_graph.add_edge(edge) new_graph.write_dot("top_20_percent_edges.dot")
注意事项
- 如果你的边label是纯数字无单位,可以直接把label转float作为权重,省略正则匹配的步骤
- 代码默认会过滤掉没有有效权重的边,如有特殊需求可以调整过滤逻辑
- 占比计算时会自动向上取整,比如总共有12条边、取前20%的情况下,会提取权重最高的3条边
内容的提问来源于stack exchange,提问作者seke
相关产品推荐
相关产品推荐

