您的位置:首页 > 其它

networkx使用笔记(四)之实战篇--数据的获取

2012-10-05 18:16 821 查看

公开的数据集

网络上针对网络的公开数据集较多,可以google斯坦福的SNAP,里面有分类的数据集

这里我用了张华平老师公布的微博数据中的关注语料库

其为xml格式,记录方式如下:

<RECORDS>
<RECORD>
<person_id>10145</person_id>
<guanzhu_id>10029</guanzhu_id>
</RECORD>
<RECORD>
<person_id>10145</person_id>
<guanzhu_id>10318</guanzhu_id>
</RECORD>
...
</RECORDS>
可以利用python十分便利的解析xml,将里面的信息解析出来。为了简单,这里解析的信息,存储在数据库中。

数据的抽取

这里介绍包括对上述xml文件的信息抽取,以及对其他文件格式,例如txt、gml等文件信息的提取。

1.xml

直接上代码

from xml.etree import ElementTree
import MySQLdb

#从xml文件中读取person_id和guanzhu_id,首先进行id的映射(因为里面的编号不是从1开始的,为了方便,这里重新编号),存入id_map表中;然后id之间的关系,存入到id_info中
def read_xml(text=r''):
root=ElementTree.fromstring(text)
eitor=root.getiterator("RECORD")
conn=MySQLdb.connect(host='localhost',user='root',passwd='root',db='python')
cursor=conn.cursor()
cursor.execute("""create table id_map(person_id BIGINT,id int )""")
cursor.execute("""create table id_info(person_id int, guanzhu_id int)""")
i=1
for e in eitor:
person_id=int(e[0].text)
guanzhu_id=int(e[1].text)
if(cursor.execute("select * from id_map where person_id=%s",person_id)==0):
cursor.execute("insert into id_map values(%s,%s)",[person_id,i])
person_id=i
i=i+1
else:
cursor.execute("select * from id_map where person_id=%s",person_id)
person_id=cursor.fetchone()[1]
if(cursor.execute("select * from id_map where person_id=%s",guanzhu_id)==0):
cursor.execute("insert into id_map values(%s,%s)",[guanzhu_id,i])
guanzhu_id=i
i=i+1
else:
cursor.execute("select * from id_map where person_id=%s",guanzhu_id)
guanzhu_id=cursor.fetchone()[1]
cursor.execute("insert into id_info values(%s,%s)",[person_id,guanzhu_id])
#print person_id, guanzhu_id
conn.commit()
conn.close()
return
'''阅读xml之前,记得删除第一行'''
read_xml(open("D:/data/guanzhu_relation.xml").read())

2. txt

这里针对如下格式:(两个数据之间用空格或tab隔开)
0	1
0	2
0	3
0	4
0	5
0	6
0	7
0	8
0	9
0	10
代码如下:

def read_text(file_name=r''):
file_read=open(file_name)
conn=MySQLdb.connect(host='localhost',user='root',passwd='root',db='python')
cursor=conn.cursor()
for line in file_read:
'''
line=line.split(' ')如果是空格隔开
'''
line=line.split('\t')
line=[line[0],line[1].replace('\n','')]
cursor.execute('insert into ndw values (%s,%s)',[line[0],line[1]])
conn.commit()
conn.close()
file_read.close()
return


3. gml文件

networkx可以直接通过函数从gml文件中读出数据。

def read_gml(file_name=r''):
file_read=open(file_name,'r')
conn=MySQLdb.connect(host='localhost',user='root',passwd='root',db='python')
cursor=conn.cursor()
H=nx.read_gml(file_read)
print H.number_of_nodes(), H.number_of_edges()
for edge in H.edges():
'''这里检测是否有重复边存在'''
if cursor.execute('select * from network where node1=%s and node2=%s',[edge[0],edge[1]])==0:
cursor.execute('insert into network values (%s,%s)',[edge[0],edge[1]])
conn.commit()
file_read.close()
conn.close()
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: