简体   繁体   中英

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.

在此处输入图片说明

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.

Is there any way to do this in 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:

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:

[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.

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')])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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