读取二分图

Read bipartite graph

我正在尝试从具有以下结构的 .txt 文件中读取图表:

115564928125997351000, ah.creativecodeapps.tiempo,1
117923818995099650007, air.com.agg.popcornmakermarket,-1
104000841215686444437, air.com.zahdoo.cadie,1
.
.
.

我一直在使用以下命令:

g=nx.read_weighted_edgelist('siatoy.txt', delimiter=',',nodetype=str,encoding='utf-8')

但是当我 g.edges(data=True) 时,我得到了这个:

[('106784557494786869271', ' com.map2app.U5635321228165120A5661458385862656'),
('106784557494786869271',' com.jb.gokeyboard.theme.mzdevelopment.americankeyboard'),
('106784557494786869271', ' com.benbasha.whoopeecushion'),
(' com.airplaneflighttakeoff', '115981152169430603941'),...]

但我想始终将数字 id 作为元组的第一个元素。请注意,我在示例中显示的列表的最后一个元素不会发生这种情况。

我怎样才能得到这个?稍后我需要遍历边缘并且我需要考虑边缘的顺序,这意味着我需要元组的第一个元素始终是数字 id。

问题是如何在阅读图表时或完成图表后实现这一目标?

一个想法是使用 str.isdigit to test if a node is numeric. (For example, see this SO answer。)然后你可以创建一个边列表,对每条边进行排序,以便数字节点排在第一位:

edges = []
for u, v, d in G.edges(data=True): # note that d contains each edge's data
    if u.isdigit(): # if u is numeric put it first
        edges.append( (u, v, d) )
    else:
        edges.append( (v, u, d) )

或单行形式:

edges = [ (u, v, d) if u.isdigit() else (v, u, d)  for u, v, d in G.edges(data=True) ]
print edges

这输出:

[('117923818995099650007', ' air.com.agg.popcornmakermarket', {'weight': -1.0}),
('104000841215686444437', ' air.com.zahdoo.cadie', {'weight': 1.0}),
('115564928125997351000', ' ah.creativecodeapps.tiempo', {'weight': 1.0})]