我希望有很多节点都有相同的标签--在我的特殊情况下,每个节点代表一篇新闻文章,它们应该用它们的新闻类别来标记。最终,我真正想要的是一个带有这些标签的GML文件。
下面是一个小样本:
Gtest = nx.Graph()
nodes = [0, 1, 2, 3, 4]
labels = {0:"business", 1:"business",2:"sports", 3:"sports", 4:"politics"}
for node in nodes:
Gtest.add_node(node)
print Gtest.nodes(data=True)
"""
this prints:
[(0, {}), (1, {}), (2, {}), (3, {}), (4, {})]
Which is good, I want 5 nodes.
"""
Gtest = nx.relabel_nodes(Gtest, labels)
print Gtest.nodes(data=True)
"""this prints:
[('business', {}), ('politics', {}), ('sports', {})]
There are only 3 nodes.
"""
nx.write_gml(Gtest, "gml/stackoverflow_test", stringizer = None)
"""
This writes the GML file:
graph [
name "()"
node [
id 0
label "business"
]
node [
id 1
label "politics"
]
node [
id 2
label "sports"
]
]
"""最后,我试图得到GML文件:
graph [
name "()"
node [
id 0
label "business"
]
node [
id 1
label "business"
]
node [
id 2
label "sports"
]
node [
id 3
label "sports"
]
node [
id 4
label "politics"
]
]是否可以为多个节点使用相同的标签/生成此输出文件?
发布于 2017-04-04 00:44:29
下面是一个如何做到这一点的例子:
G = nx.Graph()
G.add_node(1, {'label' : 'foo'})
G.add_node(2, {'label' : 'foo'})
G.nodes(data=True)
#[(1, {'label': 'foo'}), (2, {'label': 'foo'})]
nx.write_gml(G,open("foo.gml","wb"))图[ 节点 id 0 标签1 节点 id 1 标签2 ]
NB答案是networkx-1.1。它在2.0或更高版本中不起作用。相反,您可以设置节点吸引分布:
nx.set_node_attributes(G, {1: 'foo', 2: 'foo'}, 'label')
G.nodes(data=True)
#NodeDataView({1: {'label': 'foo'}, 2: {'label': 'foo'}})发布于 2020-01-24 15:43:25
您可以通过将自定义函数作为stringizer参数传递给gml函数来实现这一点。
下面是生成您想要的GML文件的代码:
import networkx as nx
class Article:
def __init__(self, id, category):
self.id = id
self.category = category
def get_category(self):
return self.category
Gtest = nx.Graph()
nodes = [0, 1, 2, 3, 4]
labels = {0: "business", 1: "business", 2: "sports", 3: "sports", 4: "politics"}
for node in nodes:
Gtest.add_node(Article(node, labels[node]))
nx.write_gml(Gtest, "articles.gml", stringizer=Article.get_category)请注意,如果在add_node中添加到图中的对象是int、float或dict,则不会调用stringizer函数。因此,上面的代码对节点使用自定义类。
https://stackoverflow.com/questions/43196192
复制相似问题