代码依赖: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 = '
![[\\S]*[\\s]\\((.*)\\)](/static/imghwm/default1.png)
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을 사용하여 Zipf의 법칙의 통계 개념을 처리하는 방법을 보여주고 법을 처리 할 때 Python의 읽기 및 대형 텍스트 파일을 정렬하는 효율성을 보여줍니다. ZIPF 분포라는 용어가 무엇을 의미하는지 궁금 할 것입니다. 이 용어를 이해하려면 먼저 Zipf의 법칙을 정의해야합니다. 걱정하지 마세요. 지침을 단순화하려고 노력할 것입니다. Zipf의 법칙 Zipf의 법칙은 단순히 : 큰 자연어 코퍼스에서 가장 자주 발생하는 단어는 두 번째 빈번한 단어, 세 번째 빈번한 단어보다 세 번, 네 번째 빈번한 단어 등 4 배나 자주 발생합니다. 예를 살펴 보겠습니다. 미국 영어로 브라운 코퍼스를 보면 가장 빈번한 단어는 "TH입니다.

이 기사에서는 HTML을 구문 분석하기 위해 파이썬 라이브러리 인 아름다운 수프를 사용하는 방법을 설명합니다. 데이터 추출, 다양한 HTML 구조 및 오류 처리 및 대안 (SEL과 같은 Find (), find_all (), select () 및 get_text ()와 같은 일반적인 방법을 자세히 설명합니다.

Python은 인터넷에서 파일을 다운로드하는 다양한 방법을 제공하며 Urllib 패키지 또는 요청 도서관을 사용하여 HTTP를 통해 다운로드 할 수 있습니다. 이 튜토리얼은 이러한 라이브러리를 사용하여 Python의 URL에서 파일을 다운로드하는 방법을 설명합니다. 도서관을 요청합니다 요청은 Python에서 가장 인기있는 라이브러리 중 하나입니다. URL에 쿼리 문자열을 수동으로 추가하지 않고 HTTP/1.1 요청을 보낼 수 있습니다. 요청 라이브러리는 다음을 포함하여 많은 기능을 수행 할 수 있습니다. 양식 데이터 추가 다중 부문 파일을 추가하십시오 파이썬 응답 데이터에 액세스하십시오 요청하십시오 머리

시끄러운 이미지를 다루는 것은 특히 휴대폰 또는 저해상도 카메라 사진에서 일반적인 문제입니다. 이 튜토리얼은 OpenCV를 사용 하여이 문제를 해결하기 위해 Python의 이미지 필터링 기술을 탐구합니다. 이미지 필터링 : 강력한 도구 이미지 필터

PDF 파일은 운영 체제, 읽기 장치 및 소프트웨어 전체에서 일관된 콘텐츠 및 레이아웃과 함께 크로스 플랫폼 호환성에 인기가 있습니다. 그러나 Python Processing Plain Text 파일과 달리 PDF 파일은 더 복잡한 구조를 가진 이진 파일이며 글꼴, 색상 및 이미지와 같은 요소를 포함합니다. 다행히도 Python의 외부 모듈로 PDF 파일을 처리하는 것은 어렵지 않습니다. 이 기사는 PYPDF2 모듈을 사용하여 PDF 파일을 열고 페이지를 인쇄하고 텍스트를 추출하는 방법을 보여줍니다. PDF 파일의 생성 및 편집에 대해서는 저의 다른 튜토리얼을 참조하십시오. 준비 핵심은 외부 모듈 PYPDF2를 사용하는 데 있습니다. 먼저 PIP를 사용하여 설치하십시오. PIP는 p입니다

이 튜토리얼은 Redis 캐싱을 활용하여 특히 Django 프레임 워크 내에서 Python 응용 프로그램의 성능을 향상시키는 방법을 보여줍니다. 우리는 Redis 설치, Django 구성 및 성능 비교를 다루어 Bene을 강조합니다.

NLP (Natural Language Processing)는 인간 언어의 자동 또는 반자동 처리입니다. NLP는 언어학과 밀접한 관련이 있으며인지 과학, 심리학, 생리학 및 수학에 대한 연구와 관련이 있습니다. 컴퓨터 과학에서

이 기사는 딥 러닝을 위해 텐서 플로와 Pytorch를 비교합니다. 데이터 준비, 모델 구축, 교육, 평가 및 배포와 관련된 단계에 대해 자세히 설명합니다. 프레임 워크, 특히 계산 포도와 관련하여 주요 차이점


핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

AI Hentai Generator
AI Hentai를 무료로 생성하십시오.

인기 기사

뜨거운 도구

드림위버 CS6
시각적 웹 개발 도구

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

Eclipse용 SAP NetWeaver 서버 어댑터
Eclipse를 SAP NetWeaver 애플리케이션 서버와 통합합니다.

mPDF
mPDF는 UTF-8로 인코딩된 HTML에서 PDF 파일을 생성할 수 있는 PHP 라이브러리입니다. 원저자인 Ian Back은 자신의 웹 사이트에서 "즉시" PDF 파일을 출력하고 다양한 언어를 처리하기 위해 mPDF를 작성했습니다. HTML2FPDF와 같은 원본 스크립트보다 유니코드 글꼴을 사용할 때 속도가 느리고 더 큰 파일을 생성하지만 CSS 스타일 등을 지원하고 많은 개선 사항이 있습니다. RTL(아랍어, 히브리어), CJK(중국어, 일본어, 한국어)를 포함한 거의 모든 언어를 지원합니다. 중첩된 블록 수준 요소(예: P, DIV)를 지원합니다.

Atom Editor Mac 버전 다운로드
가장 인기 있는 오픈 소스 편집기
