我正在尝试编写用于获取 Twitter 网络属性的代码。
但是我的代码出错了。我不知道怎么会这样。
错误是这样的:
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”是关注者,其他人是被关注者。
+
我想获得以下结果:(1) 连通分量的数量,(2) 最大连通分量中节点的分数,(3) 入度的平均值和中值,(4) 出度的平均值和中值, (5) 直径,(6) 聚类系数
但是“networkx.lanl.gov”网站无法正常工作。
有人帮帮我吗?
最佳答案
该错误与 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
>>>
因此,空行可能会导致问题。您可以明确地检查这一点,例如,通过添加
if not line:
continue
在 for
循环的开头。
另请查看 networkx.read_edgelist ,如果您不需要显示进度的 print
语句,这应该是最简单的。
关于python - 使用 Python networkx 探索网络属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8245660/