gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 17:30:22 27 4
gpt4 key购买 nike

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

enter image description here

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

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

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

但我只想得到 A/B 和 B/C 如上所述,排除其他的。

有什么办法可以在 networkx python 中做到这一点?任何解决方案表示赞赏!

最佳答案

您可以过滤掉节点,使用以下代码并简单地使用 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')])

关于python - 如何过滤 Networkx 图中具有特殊字符的节点或边,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60278227/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com