Python从数据库里筛选出关键字排行

 # 连接数据库方法
    def connect_data_base(self, sql):
        conn = pymysql.connect(host='888.88.888.888', user='xxx', password='xxxxxxx',
                               database='comment', charset='utf8')
        cursor = conn.cursor()
        cursor.execute(sql)
        outcome = cursor.fetchall()
        cursor.close()
        conn.close()
        return outcome
        
 def get_key_word(self):
        sql = "SELECT good_comment FROM comment_data WHERE comment_grade='差评'"
        comment_list = self.connect_data_base(sql)
        fall_off = []
        for get_to in comment_list:
            knock_at = get_to[0]
            fall_off.append(knock_at)
        # print(fall_off) 从数据库中拿出差评数据
        laugh_at = ''.join(fall_off) #把列表组合成字符串
        print(laugh_at)
        dict_learn = {}
        # 循环遍历列表或字符串,如果不在则创建(key,value),如果字符在字典中则值加1
        for i in laugh_at:
            if i not in dict_learn:
                dict_learn[i] = 1
            else:
                dict_learn[i] += 1
        # 找到字典中,最大的value值
        temp = max(dict_learn.values())
        print(dict_learn)
        # 把字典数据按照从大到小排序
        live_on = sorted(dict_learn.items(), key=lambda d: d[1], reverse=True)
        print(live_on)
        # 根据最大的value值,找对应的key值,打印出出现次数最多的字符
        for k, v in dict_learn.items():
            if v == temp:
                print("出现最多的是:", k, "出现了:", v)

你可能感兴趣的:(python,python,数据库,开发语言)