代码之家  ›  专栏  ›  技术社区  ›  giorgioW

使用python3表示实体之间的关系

  •  2
  • giorgioW  · 技术社区  · 7 年前

    我想使用 networkx Python3的库,但我不知道如何解决这个问题。

    基本上我有 relation 两人之间 entities 它位于一个名为 nations.csv . 看起来是这样的:

    China, Economicaid, Egypt
    China, Economicaid, Indonesia
    USSR, Economicaid, Cuba 
    USSR, Economicaid, India
    USSR, Economicaid, Poland
    UK, Economicaid, India 
    UK, Economicaid, Jordan
    USA, Economicaid, Brazil
    

    理解第一行是与第二行之间的第三行(实体2)相关的实体之一:

    relation

    我分析了csv文件,以便将每一行存储在字典中,如下所示:

    d = {}
    d['entity1'] = []
    d['relation'] = []
    d['entity2'] = []
    
    dictReader = csv.DictReader(open('nations.csv', 'rt'), fieldnames = 
    ['entity1', 'relation', 'entity2'], delimiter = ',', quotechar = '"')
    
    for row in dictReader:
        for key in row:
            d[key].append(row[key])
    

    我所做的是使用函数绘制节点 add_node() 如以下示例所示:

    import csv
    import networkx as nx
    import matplotlib.pyplot as plt
    
    
    d = {}
    d['entity1'] = []
    d['relation'] = []
    d['entity2'] = []
    
    dictReader = csv.DictReader(open('nations.csv', 'rt'), fieldnames = ['entity1', 'relation', 'entity2'], delimiter = ',', quotechar = '"')
    
    for row in dictReader:
        for key in row:
            d[key].append(row[key])
    
    print()
    
    for i in range (1, len(d['entity1'])):
        r.append(d['entity1'][i])
    
    for k in range (1, len(d['entity2'])):
        o.append(d['entity2'][k])
    
    
    G=nx.Graph()
    
    for j in range(len(r)):
        G.add_node(r[j])
        G.add_node(o[j])
    
    nx.draw_networkx(G, with_labels = True, node_size = 500)
    
    plt.show()
    

    但是,当我想表示节点之间的边时,问题就来了,因为它不仅是边本身,它还有自己的含义标签。

    1 回复  |  直到 7 年前
        1
  •  2
  •   Paul Brodersen    7 年前

    基本上,国旗 with_labels 真的应该打电话 with_node_labels 因为它仅触发节点标签的打印。因此,需要手动添加边标签( networkx.draw_networkx_edge_labels )绘制完图形(networkx.draw`)后,需要1)在同一个轴上打印,2)对两个打印使用相同的图形布局。

    import numpy as np
    import matplotlib.pyplot as plt
    import networkx as nx
    import csv
    
    # load data
    dictReader = csv.DictReader(open('nations.csv', 'rt'), fieldnames = ['entity1', 'relation', 'entity2'], delimiter = ',', quotechar = '"')
    
    # create a more amenable data structure
    edge_to_label = {(d['entity1'], d['entity2']) : d['relation'] for d in dictReader}
    
    # create graph
    G = nx.from_edgelist(edge_to_label.keys())
    
    # precompute layout (default layout used here)
    layout = nx.layout.fruchterman_reingold_layout(G)
    
    # create figure so we plot the graph and labels on the same plot
    fig, ax = plt.subplots(1,1)
    
    # draw graph
    nx.draw(G, pos=layout, ax=ax, with_labels=True)
    
    # draw labels using the same, pre-computed graph layout
    nx.draw_networkx_edge_labels(G, pos=layout, edge_labels=edge_to_label, ax=ax)
    
    plt.show()
    

    enter image description here