利用python对新浪微博用户标签进行分词并推荐相关用户
利用python对新浪微博用户标签进行分词并推荐相关用户<div id="cnblogs_post_body"> 新浪微博的开放平台的开发者日益活跃,除了商业因素外还有很大的一股民间工程师力量;大量热衷于群体行为研究与自然语言处理以及机器学习和数据挖掘的研究者 and 攻城师们开始利用新浪真实的数据和平台为用户提供更好的应用或者发现群体的行为规律包括一些统计信息,本文就是利用新浪开放平台提供的API对微博的用户标签进行分词处理,然后根据分词后的关键字给用户推荐感兴趣的人,在此记录下以备后用。
requisition:
python+sinaWeibo python SDK+ICTCLAS
备注:ICTCLAS是中国科学院计算技术研究所提供的中文分词包
开始上代码:
1.先要注册新浪开发者以获得APP_KEY和APP_SECRET
2.根据python SDK的howto根据Authou2机制获得授权(得到code进而得到access_token与expires_in),代码如下:
<div class="cnblogs_code"> 1 #-*-coding:UTF-8-*- 2 ''' 3 Created on 2012-12-10 45 @author: jixianwu 6 ''' 7 from weibo import APIClient,APIError 8 import urllib,httplib 9 10 class AppClient(object):11 ''' initialize a app client '''12 def __init__(self,*aTuple):13 self._appKey = aTuple #your app key14 self._appSecret = aTuple #your app secret15 self._callbackUrl = aTuple #your callback url16 self._account = aTuple #your weibo user name (eg.email)17 self._password = aTuple # your weibo pwd18 self.AppCli = APIClient(app_key=self._appKey,app_secret=self._appSecret,redirect_uri=self._callbackUrl)19 self._author_url = self.AppCli.get_authorize_url()20 self._getAuthorization()21 22 def __str__(self):23 return 'your app client is created with callback %s' %(self._callbackUrl)24 25 def _get_code(self):#使用该函数避免了手动输入code,实现了模拟用户授权后获得code的功能26 conn = httplib.HTTPSConnection('api.weibo.com')27 postdict = {"client_id": self._appKey,28 "redirect_uri": self._callbackUrl,29 "userId": self._account,30 "passwd": self._password,31 "isLoginSina": "0",32 "action": "submit",33 "response_type": "code",34 }35 postdata = urllib.urlencode(postdict)36 conn.request('POST', '/oauth2/authorize', postdata, {'Referer':self._author_url,'Content-Type': 'application/x-www-form-urlencoded'})37 res = conn.getresponse()38 location = res.getheader('location')39 code = location.split('=')40 conn.close()41 return code42 43 def _getAuthorization(self):#将上面函数获得的code再发送给新浪认证服务器,返回给客户端access_token和expires_in,有了这两个东西,咱就可以调用api了44 ''' get the authorization from sinaAPI with oauth2 authentication method '''45 code = self._get_code()46 r = self.AppCli.request_access_token(code)47 access_token = r.access_token # The token return by sina48 expires_in = r.expires_in49 self.AppCli.set_access_token(access_token, expires_in)
页:
[1]