我是 NetworkX 的新手,使用的是 NetworkX 2.5,并且对已弃用的代码有一些问题。代码是从这里提取的。我尝试修复一些不推荐使用的功能,但无法使代码正常工作。我也不明白 connected_components 函数是如何工作的。
panama_nodes = panama.nodes()
relabel = {}
for f, cc, name in NODES:
with open(f,encoding='utf8') as infile:
kind = f.split(".")[0]
data = csv.DictReader(infile)
names_countries = {node["node_id"] :
(node[name].strip().upper(), node[cc])
for node in data
if node["node_id"] in panama_nodes}
names = {nid: values[0] for nid, values in names_countries.items()}
countries = {nid: values[1] for nid, values in names_countries.items()}
kinds = {nid: kind for nid, _ in names_countries.items()}
nx.set_node_attributes(panama, countries, "countries")
nx.set_node_attributes(panama, kinds, "kind")
relabel.update(names)
nx.relabel_nodes(panama, relabel, copy=False)
if "ISSUES OF:" in panama:
panama.remove_node("ISSUES OF:")
if "" in panama:
panama.remove_node("")
print(nx.number_of_nodes(panama), nx.number_of_edges(panama))
components = [p.nodes() for p in nx.connected_components(panama)
if nx.number_of_nodes(p) >= 20
or nx.number_of_edges(p) >= 20]
panama0 = panama.subgraph(itertools.chain.from_iterable(components))
with open("panama-beneficiary.pickle", "wb") as outfile:
pickle.dump(panama0, outfile)
这些代码行返回一个 AttributeError:
components = [p.nodes() for p in nx.connected_components(panama)
if nx.number_of_nodes(p) >= 20
or nx.number_of_edges(p) >= 20]
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-6-108e98bba596> in <module>
----> 1 components = [p.nodes() for p in nx.connected_components(panama)
2 if nx.number_of_nodes(p) >= 20
3 or nx.number_of_edges(p) >= 20]
4
5 panama0 = panama.subgraph(itertools.chain.from_iterable(components))
<ipython-input-6-108e98bba596> in <listcomp>(.0)
1 components = [p.nodes() for p in nx.connected_components(panama)
----> 2 if nx.number_of_nodes(p) >= 20
3 or nx.number_of_edges(p) >= 20]
4
5 panama0 = panama.subgraph(itertools.chain.from_iterable(components))
~\AppData\Local\Programs\Python\Python37\lib\site-packages\networkx\classes\function.py in number_of_nodes(G)
83 def number_of_nodes(G):
84 """Returns the number of nodes in the graph."""
---> 85 return G.number_of_nodes()
86
87
AttributeError: 'set' object has no attribute 'number_of_nodes'
任何帮助表示赞赏!