2011-11-23 104 views
3

我试图让一个代码获取Twitter的网络属性。使用Python的networkx探索网络属性

但是我的代码出现了错误。我不知道它是怎么发生的。

的错误是这样的:

Traceback (most recent call last): 
    File "Network_property.py", line 14, in <module> 
    followee = line.strip().split('\t')[1] 
IndexError: list index out of range 

的代码是这样的:

import os, sys 
import time 
import networkx as nx 


DG = nx.DiGraph() 

ptime = time.time() 
j = 1 

#for line in open("./US_Health_Links.txt", 'r'): 
for line in open("./test_network.txt", 'r'): 
    follower = line.strip().split('\t')[0] 
    followee = line.strip().split('\t')[1] 

    DG.add_edge(follower, followee) 

    if j%1000000 == 0: 
     print j*1.0/1000000, "million lines done", time.time() - ptime 
     ptime = time.time() 
    j += 1 

print nx.number_connected_components(DG) 

我收集了一些链接这样的数据:

1000 1001 
1000 1020191 
1000 10267352 
1000 10957902 
1000 11039092 
1000 1118691 
1000 11882 
1000 1228281 
1000 1247041 
1000 12965332 
1000 13027572 
1000 13075072 
1000 13183162 
1000 13250162 
1000 13326292 
1000 13452672 
1000 13844892 
1000 14061830 
1000 1406481 
1000 14134703 
1000 14216951 
1000 14254402 
1000 14258044 
1000 14270791 
1000 14278978 
1000 14313332 
1000 14392970 
1000 14441172 
1000 14497568 
1000 14502775 
1000 14595635 
1000 14620544 
1000 14632615 
1000 14680596 
1000 14956164 
1000 14998341 
1000 15132211 
1000 15145450 
1000 15285998 
1000 15288974 
1000 15300187 
1000 1532061 
1000 15326300 

“1000” 是一个追随者,其他人都是followee。

+

我想获得的(1)号连接成分的结果,(2)在连接的最大组成部分节点的级分,(3)平均和的入度,(4)平均中值和(5)直径和(6)聚类系数的中位数

但是网站“networkx.lanl.gov”不起作用。

有没有人帮助我?

+1

你确定这些是'test_network.txt'中的选项卡吗?也许可以将你的两个split('\ t')'实例改为'split()',看看会发生什么。 –

+0

@DavidAlber如果你的评论是一个答案,我会upvote它... –

+0

是的,@DavidAlber你是对的!谢谢! – ooozooo

回答

1

该错误与networkx没有任何具体关系。现在发生的情况是,某些行line.strip().split('\t')仅返回一个字段。我猜想问题在于文件中的空白行。比较:

>>> ''.split("\t") 
[''] 
>>> ''.split("\t")[1] 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
IndexError: list index out of range 
>>> 

因此,空行可能会导致问题。你可以明确地检查这一点,例如,在你for循环的开头添加

if not line: 
    continue 

另请参阅networkx.read_edgelist,如果您不需要print语句显示进度,那么这应该是最简单的。

+0

感谢您的帮助!我没有仔细检查我的数据。 – ooozooo

+0

+1鉴于这种情况,空行可能是犯罪嫌疑人。 –

1

您提供的network.txt文件示例没有选项卡;它有空间。如果将split('\t')的实例更改为split(),它将在任何空格上分割,因此它将处理文件,无论它们是否具有空格或制表符。