3

我希望能够让许多节点具有相同的标签——在我的特定情况下,每个节点代表一篇新闻文章,并且应该用它们的新闻类别来标记它们。最终,我真正想要的是带有这些标签的 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"
  ]
]

是否可以为多个节点使用相同的标签/生成此输出文件?

4

2 回答 2

5

以下是如何做到这一点的示例:

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

注意答案是针对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'}})
于 2017-04-04T00:44:29.800 回答
0

您可以通过将自定义函数作为stringizer参数传递给 write_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 函数。因此,上面的代码为节点使用了一个自定义类。

于 2020-01-24T15:43:25.210 回答