[英]Create a networkx weighted graph and find the path between 2 nodes with the smallest weight
[英]How to find a path between 2 nodes based on in-between node's attribute's value using networkx graph?
我可以通过一棵树搜索并使用简单的方法获得节点之间的最短路径:
nx.shortest_path(G, source=, target=)
但是我怎样才能选择一条通过具有特定属性值的节点的路径呢?
我有带节点的简单图
G = nx.Graph()
for token in document:
G.add_node(token.orth_, item = token.i, tag = token.tag_, dep = token.dep_)
和边缘:
for token in document:
for child in token.children:
G.add_edge(token.orth_, child.orth_, pitem = token.i, citem = child.i,
ptag = token.tag_, pdep = token.dep_, ctag = child.tag_, cdep = child.dep_)
我能找到简单的解决方案吗,因为现在我正在努力构建复杂的功能。
编辑
这个想法是有一个这样的功能:(粗略)
def getPathByNode(betw_word, betw_attr, src_word, src_attr, trg_word, trg_attr):
nx.shortest_path(G, source=src, source_attr=src_attr, target=trg, target_attr=trg_attr, through=betw_word, through_attr=betw_attr)
....
但当然不是所有的参数都必须传递。 作为输入,我将举例:
source_attr = {'dep_': 'ROOT'}
target_attr = {'tag_': 'NN'}
through = "of"
or through = "from"
or through_attr = {'tag_': 'IN'}
等等。 我目前正在尝试从中间( through='from'
)开始构建递归并搜索邻居,但情况相同 - 缺少属性。
for i in G.neighbors("from"):
print(i)
我只是一个字符串。
一个简单的解决方案是计算从源到目标的所有路径。 然后过滤掉所有没有满足条件的节点的路径,在这组路径中选择最短的路径。 假设你有一个无向和未加权的图,这样的事情应该可以工作:
import networkx as nx
# Generate a sample graph:
G = nx.barabasi_albert_graph(10, 3, seed=42)
print(G.edges())
def check_attribute(G, node):
# Say the condition is node id is 3:
return node == 3
valid_paths = []
for path in nx.all_simple_paths(G, source=0, target=7):
cond = False
for node in path:
if check_attribute(G, node):
cond = True
valid_paths.append(path)
break
lengths = [len(path) for path in valid_paths]
shortest_path = valid_paths[lengths.index(min(lengths))]
print('valid paths: {}'.format(valid_paths))
print('shortest_path: {}'.format(shortest_path))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.