pythonユーザーの友達の推薦を実現

15238 ワード

通信録の権限が得られる場合は、ユーザの通信録推薦を通じて、ここではユーザとの共通の友達数に基づいて推薦するだけで簡単です.
先着コード
import pymongo
import random


class Mongodb(object):
    def __init__(self, host, port, db):
        try:
            my_client = pymongo.MongoClient(host + ':' + port)
        except Exception:
            raise Exception('Cannot connect to server')
        else:
            self.db_ais = my_client[db]


class UsersRecommend:
    def __init__(self, uuid):
        self.uuid = uuid
        self.my_db = Mongodb('mongodb://localhost', 'xxxxx', 'xxx')  #      ,  mysql
        self.res_data = list(self.my_db.db_ais['friends'].find({'status': {'$in': [2, -1]}}, {'toUserId': 1, 'userId': 1}))  #            
        self.direct_f = self.get_friends(uuid)  #     
        if len(self.direct_f) > 50:  #         50 
            self.direct_f = random.sample(self.direct_f, 50)

    def recommend_f(self, pageno, pagesize):
        if len(self.direct_f) > 0:
            indirect_f = [{'indirect_id': x, 'relations': []} for x in self.direct_f]  #        
            for x in self.res_data:  #   res_data,            
                if x['userId'] in self.direct_f and x['toUserId'] not in self.direct_f and x['toUserId'] != self.uuid:
                    indirect_f[self.direct_f.index(x['userId'])]['relations'].append(x['toUserId'])
            recommends, recommends_idx = [], []
            for x in indirect_f:
                if len(x['relations']) > 50:  #             
                    continue
                for y in x['relations']:
                    if y not in recommends_idx:
                        recommends_idx.append(y)
                        recommends.append({'uid': y, 'num': 0, 'score': 0})
                    recommends[recommends_idx.index(y)]['score'] += 1  #    ‘  ’  
                    recommends[recommends_idx.index(y)]['num'] += 1
            recommends.sort(key=lambda x: x['score'], reverse=True)  #         
            return [{'uid': x['uid'], 'common_friends': x['num']} for x in recommends][(pageno - 1) * pagesize:pageno * pagesize]  #   
        else:  #           
            return []

    #            
    def get_friends(self, usr_id):
        return [x['toUserId'] for x in self.res_data if x['userId'] == usr_id]


#   
# res = UserRecommend(10073926).recommend_f(1, 10)
# print(res)

demoでは類似度計算を共通の友達数で置き換えた.共通の友人に対しては,その友人数に基づいてscoreを計算し,類似度を求め,類似度に基づいてソートすることができる.具体的にはこのブログを参考にすることができます:友达の推薦アルゴリズム-関係に基づく推薦