欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

使用python繪制人人網(wǎng)好友關(guān)系圖示例

 更新時間:2014年04月01日 14:45:52   作者:  
這篇文章主要介紹了使用python繪制人人網(wǎng)好友關(guān)系圖示例,需要的朋友可以參考下

代碼依賴:networkx matplotlib

復(fù)制代碼 代碼如下:

 #! /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 = '<a href="http://www\\.renren\\.com/profile\\.do\\?id=(\\d+)"><img src="[\\S]*" alt="[\\S]*[\\s]\\((.*)\\)" />'

        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)

相關(guān)文章

  • Python多進程并發(fā)(multiprocessing)用法實例詳解

    Python多進程并發(fā)(multiprocessing)用法實例詳解

    這篇文章主要介紹了Python多進程并發(fā)(multiprocessing)用法,實例分析了multiprocessing模塊進程操作的相關(guān)技巧,需要的朋友可以參考下
    2015-06-06
  • python實現(xiàn)對輸入的密文加密

    python實現(xiàn)對輸入的密文加密

    這篇文章主要為大家詳細介紹了python實現(xiàn)對輸入的密文加密,分析python求解簡單加密問題,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2019-03-03
  • python中的信號通信 blinker的使用小結(jié)

    python中的信號通信 blinker的使用小結(jié)

    信號是一種通知或者說通信的方式,信號分為發(fā)送方和接收方,信號的特點就是發(fā)送端通知訂閱者發(fā)生了什么,今天通過本文給大家介紹python中的信號通信 blinker的相關(guān)知識,感興趣的朋友一起看看吧
    2021-10-10
  • python爬取w3shcool的JQuery課程并且保存到本地

    python爬取w3shcool的JQuery課程并且保存到本地

    本文主要介紹python爬取w3shcool的JQuery的課程并且保存到本地的方法解析。具有很好的參考價值。下面跟著小編一起來看下吧
    2017-04-04
  • 詳談python中subprocess shell=False與shell=True的區(qū)別

    詳談python中subprocess shell=False與shell=True的區(qū)別

    這篇文章主要介紹了詳談python中subprocess shell=False與shell=True的區(qū)別說明,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2021-04-04
  • Windows下python3.6.4安裝教程

    Windows下python3.6.4安裝教程

    這篇文章主要為大家詳細介紹了Windows下python3.6.4安裝教程,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2018-07-07
  • 教你學會使用Python正則表達式

    教你學會使用Python正則表達式

    正則表達式是一個特殊的字符序列,它能幫助你方便的檢查一個字符串是否與某種模式匹配。 Python 自1.5版本起增加了re 模塊,它提供 Perl 風格的正則表達式模式。re 模塊使 Python 語言擁有全部的正則表達式功能。
    2017-09-09
  • matplotlib 畫動態(tài)圖以及plt.ion()和plt.ioff()的使用詳解

    matplotlib 畫動態(tài)圖以及plt.ion()和plt.ioff()的使用詳解

    這篇文章主要介紹了matplotlib 畫動態(tài)圖以及plt.ion()和plt.ioff()的使用詳解,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2021-01-01
  • python遍歷字符串中每一個字符的4種方式

    python遍歷字符串中每一個字符的4種方式

    很多計算過程都需要每次從一個字符串中取一個字符,下面這篇文章主要給大家介紹了關(guān)于python遍歷字符串中每一個字符的4種方式,文中通過實例代碼介紹的非常詳細,需要的朋友可以參考下
    2023-05-05
  • Tensorflow2.4從頭訓練Word?Embedding實現(xiàn)文本分類

    Tensorflow2.4從頭訓練Word?Embedding實現(xiàn)文本分類

    這篇文章主要為大家介紹了Tensorflow2.4從頭訓練Word?Embedding實現(xiàn)文本分類,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2023-01-01

最新評論