代码依赖:networkx matplotlib

#! /bin/env python

# -*- coding: utf-8 -*-

import urllib

import urllib2

import cookielib

import re

import cPickle as p

import networkx as nx

import matplotlib.pyplot as plt

__author__ = """Reverland (lhtlyy@gmail.com)"""

# Control parameters,EDIT it here

## Login

username = 'None'

password = 'None'

## Control Graphs, Edit for better graphs as you need

label_flag = True # Whether shows labels.NOTE: configure your matplotlibrc for Chinese characters.

remove_isolated = True # Whether remove isolated nodes(less than iso_level connects)

different_size = True # Nodes for different size, bigger means more shared friends

iso_level = 10

node_size = 40 # Default node size

def login(username, password):

"""log in and return uid"""

logpage = "http://www.renren.com/ajaxLogin/login"

data = {'email': username, 'password': password}

login_data = urllib.urlencode(data)

cj = cookielib.CookieJar()

opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))

urllib2.install_opener(opener)

res = opener.open(logpage, login_data)

print "Login now ..."

html = res.read()

#print html

# Get uid

print "Getting user id of you now"

res = urllib2.urlopen("http://www.renren.com/home")

html = res.read()

# print html

uid = re.search("'ruid':'(\\d+)'", html).group(1)

# print uid

print "Login and got uid successfully"

return uid

def getfriends(uid):

"""Get the uid's friends and return the dict with uid as key,name as value."""

print "Get %s 's friend list" % str(uid)

pagenum = 0

dict1 = {}

while True:

targetpage = "http://friend.renren.com/GetFriendList.do?curpage=" + str(pagenum) + "&id=" + str(uid)

res = urllib2.urlopen(targetpage)

html = res.read()

pattern = ''

m = re.findall(pattern, html)

#print len(m)

if len(m) == 0:

break

for i in range(0, len(m)):

no = m[i][0]

uname = m[i][1]

#print uname, no

dict1[no] = uname

pagenum += 1

print "Got %s 's friends list successfully." % str(uid)

return dict1

def getdict(uid):

"""cache dict of uid in the disk."""

try:

with open(str(uid) + '.txt', 'r') as f:

dict_uid = p.load(f)

except:

with open(str(uid) + '.txt', 'w') as f:

p.dump(getfriends(uid), f)

dict_uid = getdict(uid)

return dict_uid

def getrelations(uid1, uid2):

"""receive two user id, If they are friends, return 1, otherwise 0."""

dict_uid1 = getdict(uid1)

if uid2 in dict_uid1:

return 1

else:

return 0

def getgraph(username, password):

"""Get the Graph Object and return it.

You must specify a Chinese font such as `SimHei` in ~/.matplotlib/matplotlibrc"""

uid = login(username, password)

dict_root = getdict(uid) # Get root tree

G = nx.Graph() # Create a Graph object

for uid1, uname1 in dict_root.items():

# Encode Chinese characters for matplotlib **IMPORTANT**

# if you want to draw Chinese labels,

uname1 = unicode(uname1, 'utf8')

G.add_node(uname1)

for uid2, uname2 in dict_root.items():

uname2 = unicode(uname2, 'utf8')

# Not necessary for networkx

if uid2 == uid1:

continue

if getrelations(uid1, uid2):

G.add_edge(uname1, uname2)

return G

def draw_graph(username, password, filename='graph.txt', label_flag=True, remove_isolated=True, different_size=True, iso_level=10, node_size=40):

"""Reading data from file and draw the graph.If not exists, create the file and re-scratch data from net"""

print "Generating graph..."

try:

with open(filename, 'r') as f:

G = p.load(f)

except:

G = getgraph(username, password)

with open(filename, 'w') as f:

p.dump(G, f)

#nx.draw(G)

# Judge whether remove the isolated point from graph

if remove_isolated is True:

H = nx.empty_graph()

for SG in nx.connected_component_subgraphs(G):

if SG.number_of_nodes() > iso_level:

H = nx.union(SG, H)

G = H

# Ajust graph for better presentation

if different_size is True:

L = nx.degree(G)

G.dot_size = {}

for k, v in L.items():

G.dot_size[k] = v

node_size = [G.dot_size[v] * 10 for v in G]

pos = nx.spring_layout(G, iterations=50)

nx.draw_networkx_edges(G, pos, alpha=0.2)

nx.draw_networkx_nodes(G, pos, node_size=node_size, node_color='r', alpha=0.3)

# Judge whether shows label

if label_flag is True:

nx.draw_networkx_labels(G, pos, alpha=0.5)

#nx.draw_graphviz(G)

plt.show()

return G

if __name__ == "__main__":

G = draw_graph(username, password)

python画关系网图_使用python绘制人人网好友关系图示例相关推荐

  1. python画地球代码_用Python制作中国地图、地球平面图及球形图

    绘制地图在python中主要用到的 basemap 库,这个库是 matplotlib 库中一个用于在 Python 中绘制地图上的 2D 数据的工具包. 安装库: 1.安装 geos 库:Pytho ...

  2. python画卡通人物_用Python 绘制儿童卡通人物,一起过儿童节

    又到一年一度的国际儿童节,今天我们来学习一下用 Python 的 Turtle 库绘制童年的卡通人物,一起做回年轻的那个少年. Turtle图形库,又称海龟库,是 Python 语言中一个很流行的绘制 ...

  3. python画交互式地图_使用Python构建交互式地图-入门指南

    python画交互式地图 Welcome to The Beginner's Guide to Building Interactive Maps in Python 欢迎使用Python构建交互式地 ...

  4. python画猪头_使用Python画小猪佩奇 社会人标配

    看了一些用python实现小猪佩奇画画的帖子,向自己实现下,以此记录. 社会人的标配是谁,当然是吹风机小猪佩奇身上纹. 我自己尝试画过小猪配齐但是感觉眼睛特别难画,画出来的猪头没有立体感,眼睛画不好整 ...

  5. 如何用python画金字塔形状_用 Python 画一只福鼠

    今年这个鼠年,尽管只是刚过了一个开头,但现实仿佛把我们很多年才需要经历的不好的事情,都在一瞬间抛向了我们,这个鼠年好像缺了点福气,本节我们使用 Python 画一只福鼠,为大家增添点福气,我们需要用到 ...

  6. 用python画动态樱花_利用python画一棵漂亮的樱花树,turtle画图代码大全,此处感谢知乎大佬小白...

    利用python画一棵漂亮的樱花树,turtle画图代码大全,此处感谢知乎大佬小白 此处感谢知乎大佬 小白练手 练习一下比较流行的turtle(海龟库) 画一棵漂亮的樱花树,效果如下: ps: 是动态 ...

  7. python画雪花流程图_用python画雪花,Python

    # 用Python画雪花 # 学习https://www.toutiao.com/i6787554710594257420/?tt_from=weixin&utm_campaign=clien ...

  8. 如何用python画金字塔形状_用Python画小猪佩奇,落叶树和动漫人物

    本文目录:小猪佩奇-落叶树-魔法少女 本文作者:小赖同学 ​ 最近在浏览Python文章时,无意中发现了一个好玩的画图工具turtle,看到各路大神竟然用Python画了一个图片出来,无法用言语来形容 ...

  9. 如何用python画爱心代码_用 python 画爱心代码讲解

    学计算机的男生发这个给我看是什么意思?​www.zhihu.com 原理其实挺简单的. 代码网上也有. 最难的部分前人都告诉我们了, 心形可画. 要自己推导通过泰勒各种扭也可以. 通过肉眼扭我感觉也不 ...

最新文章

  1. Android 自定义Toast实现多次触发只会显示一次toast
  2. 设置maxJsonLength,解决ajax通过POST方式调用.net的webService时,数据过长时服务器返回500错误的问题
  3. android ScrollView实现上拉、下拉更新
  4. 模拟IIC与硬件IIC的区别!
  5. c语言是结构化 模块化,c语言是完全模块化和结构化的语言,怎么理解,什么是模块化和结构化...
  6. [Bootstrap-插件使用]Jcrop+fileinput组合实现头像上传功能
  7. GitHub(从安装到使用)
  8. c语言cis,c语言小白学习历程第五篇
  9. 【通信4.0 重新发明通信网】读后感
  10. MongoDB中对象反序列化的一个小问题
  11. iwconfig命令
  12. javascript监听页面刷新事件
  13. 软件工程基础知识 二
  14. Mac终端远程连接历史记录怎么清除
  15. win7 正式版安装成功,贴图得瑟一下
  16. cad角度命令怎么输入_CAD阵列命令中角度阵列的使用技巧
  17. 2021-2022 ACM-ICPC Latin American Regional Programming Contest 题解
  18. 打印机提示 change drum soon 解决
  19. vue使用echarts中鼠标滚轮失效问题
  20. GLADE3教程(一)

热门文章

  1. PB调用.NET类库详解
  2. 用js实现改变随意改变div属性style的名称和值的结果
  3. 动手学深度学习(PyTorch实现)(九)--VGGNet模型
  4. Const 深度解析
  5. Learning中的代数结构的建立
  6. matlab画图小记tickdir\YTick\YTick
  7. 深度学习-CNN提取图像特征
  8. 7-277 单身狗 (25 分)
  9. 7-1 打印沙漏 (20 分)
  10. 奇偶链表的分割(C++)