简体   繁体   English

如何在Networkx图中过滤具有特殊字符的节点或边

[英]How to filter nodes or edges with special character in Networkx graph

I have the following NetworkX graph, G. I would like to filter only nodes having special characters for example (A/B and B/C) or edges (A/B, B/C) excluding others.我有以下 NetworkX 图 G。我只想过滤具有特殊字符的节点,例如(A/B 和 B/C)或边缘(A/B、B/C)排除其他节点。

在此处输入图片说明

I have tried with this but it is printing all information.我试过这个,但它正在打印所有信息。

G.nodes()
A,A/B, C, B/C, D

and

G.edges()
(A,A/B),(A,C), (A/B, B/C), (C,B/C), (B/C,D)

But I would like to get only A/B and B/C as mentioned above by excluding others.但是我想通过排除其他人只得到上面提到的A/B and B/C

Is there any way to do this in networkx python?有没有办法在networkx python中做到这一点? Any solution is appreciated!任何解决方案表示赞赏!

Graph nodes and edges are list-like structures so you can iterate through them and filter nodes/edges like a list:图节点和边是类似列表的结构,因此您可以遍历它们并像列表一样过滤节点/边:

import networkx as nx

G = nx.DiGraph()
G.add_edges_from([
    ('A', 'A/B'),
    ('A/B', 'B/C'),
    ('A', 'C'),
    ('B/C', 'D')
])

Filter all nodes with B symbol in them:过滤所有带有B符号的节点:

list(filter(lambda x: 'B' in x, G.nodes))

['B/C', 'A/B']

Filter all nodes with / symbol in them (another way to do the same thing):过滤所有带有/符号的节点(另一种做同样事情的方式):

[n for n in G.nodes if '/' in n]

['B/C', 'A/B']

Filter all edges with B symbol in any node of the edge:在边的任何节点中过滤所有带有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')]

Filter all edges with / symbol in each node of the edge:在边的每个节点中用/符号过滤所有边:

[e for e in G.edges if '/' in e[0] and '/' in e[1]]

[('A/B', 'B/C')]

You can filter out the nodes, using the following code and simply use nx.subgraph function to get the subgraph.您可以使用以下代码过滤掉节点,只需使用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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM