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

Python 如何在Networkx图形中过滤具有特殊字符的节点或边,python,graph,networkx,Python,Graph,Networkx,我有下面的NetworkX图,G。我只想筛选具有特殊字符(例如A/B和B/C)或边(A/B、B/C)的节点,不包括其他节点 我试过这个,但它正在打印所有信息 G.nodes() A,A/B, C, B/C, D 及 但是我只想通过排除其他人来获得上面提到的A/B和B/C 在networkx python中有什么方法可以做到这一点吗?任何解决方案都将不胜感激 图形节点和边是类似列表的结构,因此您可以对它们进行迭代,并像列表一样过滤节点/边: import networkx as nx G =

我有下面的NetworkX图,G。我只想筛选具有特殊字符(例如A/B和B/C)或边(A/B、B/C)的节点,不包括其他节点

我试过这个,但它正在打印所有信息

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

但是我只想通过排除其他人来获得上面提到的
A/B和B/C


在networkx python中有什么方法可以做到这一点吗?任何解决方案都将不胜感激

图形节点和边是类似列表的结构,因此您可以对它们进行迭代,并像列表一样过滤节点/边:

import networkx as nx

G = nx.DiGraph()
G.add_edges_from([
    ('A', 'A/B'),
    ('A/B', 'B/C'),
    ('A', 'C'),
    ('B/C', 'D')
])
过滤其中包含
B
符号的所有节点:

列表(过滤器(λx:B在x,G.nodes中))

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

使用
/
符号筛选所有节点(执行相同操作的另一种方法):

[n表示G.nodes中的n,如果n中的“/”

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

使用边的任何节点中的
B
符号过滤所有边:

[e代表e,如果e[0]中的“B”或e[1]中的“B”,则表示e的边]

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

在边的每个节点中使用
/
符号过滤所有边:

[e表示e在e[0]中的“/”和e[1]中的“/”时的G.边]

[(“A/B”、“B/C”)]


您可以使用以下代码筛选出节点,只需使用函数即可获得子图

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