如何在Networkx中找到具有Python字符串匹配功能的节点?

问题描述 投票:1回答:1

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

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})?)$

python regex networkx shortest-path
1个回答
1
投票

你可以分两步完成,而不必循环。

  • 步骤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)

产生:

enter image description here

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

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)]

希望能帮助你前进。

© www.soinside.com 2019 - 2024. All rights reserved.