首页 > 解决方案 > 如何在 Networkx 中查找具有 Python 字符串匹配函数的节点?

问题描述

给定一个依赖解析图,如果我想找到两个固定节点之间的最短路径长度,这就是我的编码方式:

nx.shortest_path_length (graph, source='cost', target='20.4')

我的问题是:如果我想匹配图表中的所有句子或收集任何数字格式近似为货币的目标怎么办?我是否必须首先找到图中作为货币的每个节点,然后遍历货币值集?

理想的情况是:

nx.shortest_path_length (graph, source='cost', target=r'^[$€£]?(\d+([\.,]00)?)$')

或来自@bluepnume ^[$€£]?((([1-5],?)?\d{2,3}|[5-9])(\.\d{2})?)$

标签: pythonregexnetworkxshortest-path

解决方案


您可以分两步完成,而无需循环。

  • 第 1 步:计算从“成本”节点到所有可达节点的最短距离。
  • 第 2 步:仅对您感兴趣的货币节点进行子集(使用正则表达式)。

这里有一个例子来说明。

import networkx as nx
import matplotlib.pyplot as plt
import re

g = nx.DiGraph()    
#create a dummy graph for illustration
g.add_edges_from([('cost','apples'),('cost', 'of'),
                  ('$2', 'pears'),('lemon', '£1.414'),
                  ('apples', '$2'),('lemon', '£1.414'),
                  ('€3.5', 'lemon'),('pears', '€3.5'),
                 ], distance=0.5) # using a list of edge tuples & specifying distance
g.add_edges_from([('€3.5', 'lemon'),('of', '€3.5')], 
                 distance=0.7)
nx.draw(g, with_labels=True)

产生:

在此处输入图像描述

现在,您可以计算到您感兴趣的节点的最短路径,使用您想要的正则表达式进行子集化。

paths = nx.single_source_dijkstra_path(g, 'cost')
lengths=nx.single_source_dijkstra_path_length(g,'cost', weight='distance')

currency_nodes = [ n for n in lengths.keys() if re.findall('(\$|€|£)',n)]

[(n,len) for (n,len) in lengths.items() if n in currency_nodes]

产生:

[('$2', 1.0), ('€3.5', 1.2), ('£1.414', 2.4)]

希望能帮助你前进。


推荐阅读