在图形工具中导入 txt 文件
Import txt file in graph-tool
我有一个定向加权网络存储在 txt 文件中,作为 3 个元素的列表:
node1 node2 weight
node1 node3 weight
...
例如三胞胎:
1 10 50
意味着我在节点 1 和节点 10 之间有一条边,权重为 50。
有人可以详细解释一下我如何将其导入图形工具以使用 SBM 执行社区检测分析。
非常感谢。
我假设对于加权图,您希望使用 PropertyMaps (https://graph-tool.skewed.de/static/doc/quickstart.html#sec-property-maps)?
要导入文件,您需要使用文件对象 (https://docs.python.org/3/tutorial/inputoutput.html)。
综上所述,您需要的代码如下:
#imports the graph-tools library
from graph_tool.all import *
#opens your file in mode "read"
f = open("your_file.txt","r")
#splits each line into a list of integers
lines = [[int(n) for n in x.split()] for x in f.readlines()]
#closes the file
f.close()
#makes the graph
g = Graph()
#adds enough vertices (the "1 + " is for position 0)
g.add_vertex(1 + max([l[0] for l in lines] + [l[1] for l in lines]))
#makes a "property map" to weight the edges
property_map = g.new_edge_property("int")
#for each line
for line in lines:
#make a new edge
g.add_edge(g.vertex(line[0]),g.vertex(line[1]))
#weight it
property_map[g.edge(g.vertex(line[0]),g.vertex(line[1]))] = line[2]
graph_tool.load_graph_from_csv(file_name, csv_options={'delimiter': ' ', 'quotechar': '"'})
这将帮助您加载带有分隔符=space 的 csv 文件。我仍在尝试阅读有关如何将权重与边缘相关联的文档:https://graph-tool.skewed.de/static/doc/graph_tool.html?highlight=load#graph_tool.Graph.load
我有一个定向加权网络存储在 txt 文件中,作为 3 个元素的列表:
node1 node2 weight
node1 node3 weight
...
例如三胞胎:
1 10 50
意味着我在节点 1 和节点 10 之间有一条边,权重为 50。
有人可以详细解释一下我如何将其导入图形工具以使用 SBM 执行社区检测分析。
非常感谢。
我假设对于加权图,您希望使用 PropertyMaps (https://graph-tool.skewed.de/static/doc/quickstart.html#sec-property-maps)?
要导入文件,您需要使用文件对象 (https://docs.python.org/3/tutorial/inputoutput.html)。
综上所述,您需要的代码如下:
#imports the graph-tools library
from graph_tool.all import *
#opens your file in mode "read"
f = open("your_file.txt","r")
#splits each line into a list of integers
lines = [[int(n) for n in x.split()] for x in f.readlines()]
#closes the file
f.close()
#makes the graph
g = Graph()
#adds enough vertices (the "1 + " is for position 0)
g.add_vertex(1 + max([l[0] for l in lines] + [l[1] for l in lines]))
#makes a "property map" to weight the edges
property_map = g.new_edge_property("int")
#for each line
for line in lines:
#make a new edge
g.add_edge(g.vertex(line[0]),g.vertex(line[1]))
#weight it
property_map[g.edge(g.vertex(line[0]),g.vertex(line[1]))] = line[2]
graph_tool.load_graph_from_csv(file_name, csv_options={'delimiter': ' ', 'quotechar': '"'})
这将帮助您加载带有分隔符=space 的 csv 文件。我仍在尝试阅读有关如何将权重与边缘相关联的文档:https://graph-tool.skewed.de/static/doc/graph_tool.html?highlight=load#graph_tool.Graph.load