python - 如何在 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})?)$
解决方案
您可以分两步完成,而无需循环。
- 第 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)]
希望能帮助你前进。
推荐阅读
- python - 如何恢复 pip freeze > requirements.txt?
- ansible - 错误!'copy' 不是 Play 的有效属性
- c++ - 拥有“受保护的非虚拟析构函数”与“受保护的虚拟析构函数”有什么好处?
- python - 按列中选定行分组
- c - 如何使用 gcc 在 windows 上编译 LIBVLC 示例代码
- ios - 我的应用程序关闭后如何保存结构?
- mysql - Amazon RDS:您尝试将用户“master”连接到 MySQL 服务器失败
- matlab - 如何在 MATLAB 中对慢速代码进行矢量化以提高性能?
- c - 如果 (n!=0) n=0; v/sn=0;哪个更有效,为什么?
- python - 从 QComboBox 中选择字符串并将 ID 插入 SQLite db