[英]How to filter nodes or edges with special character in Networkx graph
图节点和边是类似列表的结构,因此您可以遍历它们并像列表一样过滤节点/边:
import networkx as nx
G = nx.DiGraph()
G.add_edges_from([
('A', 'A/B'),
('A/B', 'B/C'),
('A', 'C'),
('B/C', 'D')
])
过滤所有带有B
符号的节点:
list(filter(lambda x: 'B' in x, G.nodes))
['B/C', 'A/B']
过滤所有带有/
符号的节点(另一种做同样事情的方式):
[n for n in G.nodes if '/' in n]
['B/C', 'A/B']
在边的任何节点中过滤所有带有B
符号的边:
[e for e in G.edges if 'B' in e[0] or 'B' in e[1]]
[('A', 'A/B'), ('B/C', 'D'), ('A/B', 'B/C')]
在边的每个节点中用/
符号过滤所有边:
[e for e in G.edges if '/' in e[0] and '/' in e[1]]
[('A/B', 'B/C')]
您可以使用以下代码过滤掉节点,只需使用nx.subgraph函数即可获取子图。
import networkx as nx
G = nx.DiGraph()
G.add_edge('A', 'C')
G.add_edge('A', 'A/B')
G.add_edge('A', 'C')
G.add_edge('A/B', 'B/C')
G.add_edge('C', 'B/C')
G.add_edge('B/C', 'D')
# This will pick up nodes containing any
# special character in them
from string import punctuation
special_chars = set(punctuation)
all_nodes = G.nodes()
special_nodes = []
for node in all_nodes:
for ch in special_chars:
if ch in node:
special_nodes.append(node)
break
H = nx.subgraph(G, special_nodes)
H.nodes()
# NodeView(('A/B', 'B/C'))
H.edges()
# OutEdgeView([('A/B', 'B/C')])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.