如何在 Networkx 中查找具有 Python 字符串匹配函数的节点?
How to find nodes with Python string matching functions in Networkx?
给定一个依赖解析图,如果我想找到两个固定节点之间的最短路径长度,我是这样编码的:
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 步:计算从您的 'cost' 节点到所有可达节点的最短距离。
- 第 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'),
('', 'pears'),('lemon', '£1.414'),
('apples', ''),('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]
产生:
[('', 1.0), ('€3.5', 1.2), ('£1.414', 2.4)]
希望能帮助您前进。
给定一个依赖解析图,如果我想找到两个固定节点之间的最短路径长度,我是这样编码的:
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 步:计算从您的 'cost' 节点到所有可达节点的最短距离。
- 第 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'),
('', 'pears'),('lemon', '£1.414'),
('apples', ''),('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]
产生:
[('', 1.0), ('€3.5', 1.2), ('£1.414', 2.4)]
希望能帮助您前进。