使用Python
想通过图形化的方式显示社交网络特定用户的好友关系,上网找了一下这方面的图形库有networkx、graphviz等,找了好久我选择了iGraph这个图形库。
igraph在Windows下的安装稍微有点麻烦,详情参见:https://my.oschina.net/stu51/blog/335455
fans.txt 和 follow.txt分别保存了爬取下来的粉丝昵称以及关注人昵称。
#coding=utf-8 from igraph import * count_fans=0 #粉丝数 count_following=0 #关注人数 fans_name=[] #粉丝昵称 following=[] #关注人昵称 #打开爬取下的昵称文件 with open('fans.txt','r') as f: lines=f.readlines() for line in lines: if (line!=None)&(line!='\n'): fans_name.append(line) # print fans_name count_fans+=1 with open('follow.txt','r') as c: lines=c.readlines() for line in lines: if (line!=None)&(line!='\n'): following.append(line) count_following+=1 g = Graph() #创建 g.add_vertices(3+count_fans+count_following) g.add_edges([(0,1),(1,2)]) g.vs[0]["name"]='Ta的粉丝' g.vs[1]["name"]='目标用户' g.vs[2]["name"]='Ta的关注' g.es["trunk"] = [True, True] g.vs["main_node"]=[1.5,3,1.5] for i in range(3,count_fans+3): g.add_edges((0,i)) g.es[i-1]["trunk"]=False for j in range(count_fans+3,3+count_fans+count_following): g.add_edges((2,j)) g.es[j-1]["trunk"]=False index=3 for fans in fans_name: g.vs[index]["name"]=fans g.vs[index]["main_node"]=False index+=1 for name in following: g.vs[index]["name"]=name g.vs[index]["main_node"]=False index+=1 visual_style = {} color_dic={1.5:"#cfe6ff",3:"#7299a7",False:"#cfe6ff"} visual_style["vertex_label_size"]=11 visual_style["vertex_label_dist"]=1 visual_style["vertex_shape"]="circle" visual_style["vertex_size"] = [7+ 10*int(main_node) for main_node in g.vs["main_node"]] visual_style["edge_width"] = [1 + 2 * int(trunk) for trunk in g.es["trunk"]] visual_style["vertex_color"] =[color_dic[main_node] for main_node in g.vs["main_node"]] visual_style["vertex_label"] = g.vs["name"] visual_style["bbox"] = (1000, 1000) visual_style["margin"] = 150 layout = g.layout("grid_fr") visual_style["layout"] = layout plot(g, **visual_style)
最终结果如图:
以上只演示了一个用户的社交关系图,有精力的话可以尝试递归地一层一层爬下去,想象一下最终绘出来的图也是挺炫酷的。
网址:使用Python http://c.mxgxt.com/news/view/923304
相关内容
八爪鱼与python结合使用微博舆情分析:使用Python进行深度解析
如何使用Python进行社交网络分析
(转载)Python 的 JPype 模块调用 Jar 包
python画明星
八爪鱼和python爬虫哪个好
利用python构建知识图谱,在neo4j里显示不了关系,如何解决?
Python基于network模块制作电影人物关系图
比速度,Python爬虫还是八爪鱼?测评两款网络爬虫工具
微博数据可视化分析:利用Python构建信息图表展示话题热度