如何将未连接的 networkx 图分成多个相互连接的互不相交的图?

How to separate an unconnected networkx graph into multiple mutually disjoint graphs that are connected?

我有一个 networkx.Graph 对象代表一个 graph whose nodes represent English words, and whose edges between two wnodes imply that the two words that those nodes represent have at least one shared cognitive synonym between their synsets (i.e. a non-empty intersection)。我希望这对某些人来说是有趣或有用的背景,但我的问题是与图表 networkx 和 Python.

有关的更广泛适用的问题

很多induced subgraphs (edge-induced, or vertex-induced) of this graph are both edge disjoint and vertex disjoint, and I'd like to separate these subgraphs into their own networkx.Graph objects such that they're connected and mutually disjoint. It is possible that I'm just using the wrong search terms for the networkx documentation, but I didn't see anything promising related to "disjoint"。以下是图表一小部分的一些示例。

我看了search results for [networkx] disjoint on Stack Overflow and didn't see what I was looking for. For example, one result talked about getting the induced subgraph when there's already have an edge set to induce from. Or another post talked about trying to draw two disjoint graphs, but that's assuming you already have them. Related to the graph theory aspect of my question, but not the networkx aspect, is that apparently there's .

现在,作为一个最小的工作示例,让我们创建一个小的随机图,但要确保它是断开连接的。

import networkx as nx

g = nx.fast_gnp_random_graph(10, 0.3)

while nx.is_connected(g):
    g = nx.fast_gnp_random_graph(10, 0.3)

此时,我们有一个图g。我在想的是像下面这样的东西,我在其中占据了一个相互不相交的图表列表。我不仅需要在遍历节点时添加更多图表,还需要随时更新图表。我认为导出图的并集可能会起作用,但是 nx.disjoint_union_allnx.union 要么通过重新标记(我不希望这样)强制图不相交,要么期望图已经是不相交。

graphs = []

for node in g.nodes(): # same 'g' we made above
    if graphs:
        pass
    else:
        graphs.append(g.subgraph([i for i in g.neighbors(node)] +\
                                 [node]).copy())

如何将一个未连接的 networkx 图分成多个相互不相交的连接图?

您似乎在寻找连通分量。
考虑下图。

components = [g.subgraph(c).copy() for c in nx.connected_components(g)]
for idx,g in enumerate(components,start=1):
    print(f"Component {idx}: Nodes: {g.nodes()} Edges: {g.edges()}")

输出:

Component 1: Nodes: [0, 1, 2, 5, 6, 7, 8, 9] Edges: [(0, 2), (0, 6), (1, 2), (1, 5), (1, 7), (1, 8), (2, 5), (5, 7), (6, 8), (7, 9), (8, 9)]
Component 2: Nodes: [3, 4] Edges: [(3, 4)]