python - 如何在Networkx中使用Python字符串匹配函数查找节点?

标签 python regex networkx shortest-path

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

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

最佳答案

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

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

希望能帮助您前进。

关于python - 如何在Networkx中使用Python字符串匹配函数查找节点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50775470/

相关文章:

python - 在 networkx/python 中为 * 搜索启发式分配 x、y 坐标

python - 如何使用networkx找到距源节点距离为2的节点?

python - 我的 while 循环永远不会到达条件语句并不断循环

python - 将 Pandas Dataframe 单元格中的嵌套数组值拆分为多行

Java模式匹配器查找多个字符串

c# - 获取字符串中模式的匹配项

python-3.x - 属性错误 : module 'networkx.algorithms.community' has no attribute 'best_partition'

python - 如何为 Scikit Learn 重新格式化分类 Pandas 变量

python - 2x2矩阵中元素的所有组合,行和列的总和等于指定的值

r - 将前后单词连接到与 R 中的条件匹配的单词