【问题标题】:Import txt file in graph-tool在图形工具中导入 txt 文件
【发布时间】:2017-01-12 17:57:15
【问题描述】:

我有一个有向加权网络存储在 txt 文件中作为 3 个元素的列表:

node1 node2 weight
node1 node3 weight
...

例如三元组:

1 10 50

表示我在节点 1 和节点 10 之间获得了一条边,权重为 50。

谁能详细解释我如何将其导入图形工具以使用 SBM 执行社区检测分析。

非常感谢。

【问题讨论】:

    标签: python import graph-tool


    【解决方案1】:

    我假设对于加权图,您希望使用 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]
    

    【讨论】:

      【解决方案2】:
      graph_tool.load_graph_from_csv(file_name, csv_options={'delimiter': ' ', 'quotechar': '"'}) 
      

      这将帮助您加载带有分隔符=空格的 csv 文件。我仍在尝试阅读有关如何将权重与边缘相关联的文档:https://graph-tool.skewed.de/static/doc/graph_tool.html?highlight=load#graph_tool.Graph.load

      【讨论】:

      • 你好@Deeksha,你知道如何加载权重吗?谢谢!
      猜你喜欢
      • 2021-02-26
      • 2015-05-04
      • 1970-01-01
      • 2020-02-01
      • 1970-01-01
      • 2019-12-20
      • 1970-01-01
      • 2011-11-18
      • 2015-08-26
      相关资源
      最近更新 更多