如果我想要找到两个固定节点之间的最短路径长度,那么给出一个依赖分析图,我就是这样编码的:
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})?)$
发布于 2018-06-11 07:09:22
您可以分两步完成,而不需要循环。
这里有一个例子来说明。
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)它产生:

现在,您可以计算出您感兴趣的节点的最短路径,并根据您的意愿使用regex对其进行细分。
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)]希望这能帮你继续前进。
https://stackoverflow.com/questions/50775470
复制相似问题