mvp.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693
  1. from mysql_db import MysqlDB
  2. from excel_util import ExcelUtil
  3. import time
  4. from entity import PeopleInfo
  5. class Mvp:
  6. """
  7. ce mvp 答题数据统计
  8. 城市特例 北京市,上海市, 重庆市,天津市
  9. """
  10. age_dict = {
  11. '00-04年生': '00后',
  12. '05-09年生': '05后',
  13. '50-59年生': '50后',
  14. '60-69年生': '60后',
  15. '70-74年生': '70后',
  16. '75-79年生': '75后',
  17. '80-84年生': '80后',
  18. '85-89年生': '85后',
  19. '90-94年生': '90后',
  20. '95-99年生': '95后'
  21. }
  22. tag_table = {
  23. '用户画像-审美偏好': ['mvp_crowd_info_aesthetic_preference', 'aesthetic_preference'],
  24. '用户画像-行为兴趣': ['mvp_crowd_info_behavior', 'behavioral_interest'],
  25. '用户画像-观念': ['mvp_crowd_info_consumer_concept', ''],
  26. '用户画像-消费特征': ['mvp_crowd_info_consumer_structure', ''],
  27. '空间需求图谱-功能关联': ['mvp_crowd_info_functional_module', ''],
  28. '性别比例': ['mvp_crowd_info_gender_rate', ''],
  29. '用户画像-生活方式': ['mvp_crowd_info_life_style', ''],
  30. '人群占比': ['mvp_crowd_info_rate', ''],
  31. '用户画像-社交模式': ['mvp_crowd_info_social_mode', ''],
  32. '用户画像-行业': ['mvp_crowd_info_trade', ''],
  33. '用户画像-出行方式': ['mvp_crowd_info_trip_mode', ''],
  34. '空间需求图谱-基础模块分值': ['mvp_innovate_space_base_module', ''],
  35. '空间需求图谱-色相': ['mvp_innovate_space_color_prefer', 'color'],
  36. '空间需求图谱-精装关注点': ['mvp_innovate_space_hardcover_focus', 'hardcover_focus'],
  37. '空间需求图谱-色调': ['mvp_innovate_space_hue_prefer', 'hue'],
  38. '空间需求图谱-单品偏好': ['mvp_innovate_space_item_preference', 'item_preference'],
  39. '空间需求图谱-材质': ['mvp_innovate_space_material_prefer', 'material'],
  40. '空间需求图谱-空间特性偏好': ['mvp_innovate_space_space_prefer', 'space_preference'],
  41. '空间需求图谱-空间拓普图': ['mvp_innovate_space_space_top', ''],
  42. '模块分数': ['mvp_crowd_info_module', 'module_name']
  43. }
  44. crowd_info_1 = {
  45. '1973': 'A',
  46. '1974': 'B',
  47. '1975': 'C',
  48. '1976': 'D',
  49. '1977': 'E',
  50. '1978': 'F',
  51. '1979': 'G',
  52. }
  53. base_insert_sql = 'insert into {}(crowd_info_id, {}, standard_value, status) values(%s, %s, %s, '\
  54. '1) '
  55. def get_table_name(self, name):
  56. """
  57. 获取表名
  58. :param name:
  59. :return:
  60. """
  61. params = self.tag_table.get(name)
  62. if params:
  63. return self.tag_table.get(name)[0]
  64. def get_insert_sql(self, tag_type_name):
  65. """
  66. 根据标签分类名称获取相应表的插入sql
  67. :param tag_type_name:
  68. :return:
  69. """
  70. params = self.tag_table.get(tag_type_name)
  71. if params:
  72. return self.base_insert_sql.format(params[0], [1])
  73. crowd = ['A', 'B', 'C', 'D', 'E', 'F']
  74. # 获取答题记录中城市列表
  75. sql_1 = 'select city from f_t_daren_score_2 group by city'
  76. # 获取父选项和父题id
  77. sql_2 = 'select a.id, a.content, b.id, b.name from bq_option a left join bq_question b on a.question_id = b.id ' \
  78. 'where a.serial_number = %s and b.serial_number = %s and a.status = b.status = 1 '
  79. # 获取答题人的年龄段集合
  80. sql_4 = 'select nld from f_t_daren_score_2 group by nld'
  81. # 根据城市,年龄段,人群分类统计答题记录数
  82. sql_5 = 'select testcase_id, COUNT(uuid) from f_t_daren_score_2 where uuid in %s group by testcase_id '
  83. # 根据父选项获取子选项id列表
  84. sql_6 = 'SELECT c.id, c.sub_question_id, c.content FROM bq_sub_option c WHERE c.father_id in (SELECT a.id FROM ' \
  85. 'bq_option a ' \
  86. 'LEFT JOIN bq_question b ON a.question_id = b.id WHERE a.serial_number = %s AND b.serial_number = %s ' \
  87. 'and a.status = 1 and b.status = 1) and c.status = 1 '
  88. # 根据子题id获取包含子题id的测试
  89. sql_7 = 'select id from bq_testcase where status = 1 and FIND_IN_SET(%s, question_ids)'
  90. # 根据子选项id统计答题数
  91. sql_8 = 'SELECT count(1) FROM f_t_daren_score_2 a LEFT JOIN d_shangju_tiku_02 b ON a.sub_question_id = ' \
  92. 'b.sub_question_id AND (a.score = b.score or a.score = b.sub_option_id) and a.testcase_id = ' \
  93. 'b.testcase_id WHERE b.sub_option_id in %s and a.uuid in %s '
  94. # 获取一个uuid下答题的子选项id列表
  95. sql_10 = 'select DISTINCT uuid, GROUP_CONCAT(DISTINCT b.sub_option_id) from f_t_daren_score_2 a left join ' \
  96. 'd_shangju_tiku_02 b on a.sub_question_id = b.sub_question_id and (a.score = b.score or a.score = ' \
  97. 'b.sub_option_id) where a.status = ' \
  98. 'b.status = 1 group by uuid '
  99. # 向表mvp_crowd_info插入数据
  100. sql_11 = 'insert into mvp_crowd_info(age_area, city_name, crowd_type, status) values(%s, %s, %s, 1)'
  101. # 向表mvp_crowd_info_behavior中插入数据
  102. sql_12 = 'insert into mvp_crowd_info_behavior(crowd_info_id, behavioral_interest, standard_value, status) values(' \
  103. '%s, %s, ' \
  104. '%s, 1) '
  105. # 向表mvp_crowd_info_module中插入数据
  106. sql_13 = 'insert into mvp_crowd_info_module(crowd_info_id, module_name, standard_value, status) values (%s, %s, ' \
  107. '%s, 1) '
  108. sql_14 = 'select a.id, a.age_area, a.city_name, a.crowd_type from mvp_crowd_info a where a.status = 1'
  109. # 获取答题城市信息from city
  110. sql_15 = '''
  111. SELECT
  112. a.uuid,
  113. IFNULL(GROUP_CONCAT(DISTINCT a.city, a.province), 00) AS city,
  114. IFNULL(GROUP_CONCAT(DISTINCT a.nld), 00) AS nld,
  115. IFNULL(GROUP_CONCAT(DISTINCT a.sex), 00) AS sex,
  116. IFNULL(GROUP_CONCAT(DISTINCT b.sub_option_id), 00) as sub_option_ids,
  117. IFNULL(GROUP_CONCAT(DISTINCT a.testcase_id), 00) as testcase_ids
  118. FROM
  119. f_t_daren_score_2 a
  120. LEFT JOIN d_shangju_tiku_02 b ON a.testcase_id = b.testcase_id
  121. WHERE
  122. a.testcase_id = b.testcase_id
  123. AND a.sub_question_id = b.sub_question_id
  124. AND (
  125. a.score = b.score
  126. OR a.score = b.sub_option_id
  127. )
  128. GROUP BY
  129. a.uuid
  130. '''
  131. # 根据用户uuid获取城市信息
  132. sql_16 = 'SELECT a.uuid, b.sub_option_content FROM f_t_daren_score_2 a LEFT JOIN d_shangju_tiku_02 b ON ' \
  133. 'a.testcase_id = b.testcase_id WHERE a.sub_question_id = b.sub_question_id AND (a.score = b.score OR ' \
  134. 'a.score = b.sub_option_id) AND a.uuid = %s AND a.sub_question_id = 303 and a.status = b.status = 1 '
  135. # 答题人人群分类信息
  136. sql_17 = 'SELECT a.uuid, b.sub_option_id FROM f_t_daren_score_2 a LEFT JOIN d_shangju_tiku_02 b ON a.testcase_id ' \
  137. '= b.testcase_id WHERE a.sub_question_id = b.sub_question_id AND (a.score = b.score OR a.score = ' \
  138. 'b.sub_option_id) AND a.uuid = %s AND a.sub_question_id = 286 and a.status = b.status = 1 '
  139. def __init__(self, path=None):
  140. self.shangju_db = MysqlDB('shangju')
  141. self.marketing_db = MysqlDB('bi_report')
  142. # self.shangju_db.truncate('mvp_standard_score')
  143. self.tag_data = ExcelUtil(file_name=path).init_mvp_data()
  144. self.crowd_info = ExcelUtil(file_name=path, sheet_name='选项-人群分类对应表').init_crowd_info()
  145. self.citys = self.init_city()
  146. self.age = self.init_age()
  147. self.people_sub_option_ids = self.marketing_db.select(self.sql_10)
  148. self.crowd_contain_sub_option_ids = self.get_crowd_contain_sub_option_ids()
  149. self.module_scores = ExcelUtil(file_name='set-behavior-tag.xlsx', sheet_name='算法关系表').init_module_info()
  150. # self.scores_tag = ExcelUtil(file_name='行为与模块分值汇总.xlsx', sheet_name='行为').init_scores()
  151. # self.score_module = ExcelUtil(file_name='行为与模块分值汇总.xlsx', sheet_name='模块').init_scores()
  152. self.scores_tag = None
  153. self.score_module = None
  154. def close(self):
  155. self.shangju_db.close()
  156. self.marketing_db.close()
  157. def init_city(self):
  158. """
  159. 获取答题数据中的城市。
  160. :return:
  161. """
  162. citys = ['宁波市', '上海市', '苏州市', '无锡市', '宁波市']
  163. # citys_info = self.marketing_db.select(self.sql_1)
  164. # citys.extend([x[0] for x in citys_info if x[0] is not None])
  165. return citys
  166. def query_behavioral_info(self, city=None, age=None, crowd=None):
  167. """
  168. 查询行为兴趣信息
  169. :return:
  170. """
  171. # datas = []
  172. # for key in self.tag_data.keys():
  173. # values = self.tag_data[key]
  174. # for value in values:
  175. # question = value[0].split('-')[0]
  176. # option = value[0].split('-')[1]
  177. # corr = value[1]
  178. # data = self.shangju_db.select(self.sql_2, [option, question])
  179. # if len(data) > 0:
  180. # print([question, option, data[0][3], data[0][1], key, corr])
  181. # datas.append([question, option, data[0][3], data[0][1], key, corr])
  182. # self.shangju_db.truncate('mvp_question_classification')
  183. # self.shangju_db.add_some(self.sql_3, datas)
  184. scores_behavioral = self.city_age_crowd(city, age, crowd)
  185. # scores_module = self.module_score(crowd, city, age, scores_behavioral['score'])
  186. # result = {'行为兴趣分值': scores_behavioral['score'], '模块分值': scores_module}
  187. print('update finished!!!')
  188. return scores_behavioral
  189. def people_info(self):
  190. """
  191. 答题人个人信息获取
  192. :return:
  193. """
  194. people_info_city = self.marketing_db.select(self.sql_15)
  195. people_infos = []
  196. for people in people_info_city:
  197. uuid = people[0]
  198. city = people[1]
  199. nld = people[2]
  200. sex = people[3]
  201. sub_option_ids_1 = people[4]
  202. testcaseid = people[5]
  203. if str(city).find('市') != -1:
  204. city = str(city).split('市')[0] + '市'
  205. if str(nld).find(',') != -1:
  206. nld_1 = list(str(nld).split(','))
  207. if len(nld_1) > 0:
  208. nld = nld_1[0]
  209. else:
  210. pass
  211. crowd = []
  212. if testcaseid:
  213. testcastids = list(map(int, str(testcaseid).split(',')))
  214. if len(testcastids) > 0:
  215. gt_75 = [x for x in testcastids if x in [75, 76, 77, 78]]
  216. if city is None and len(gt_75) > 0:
  217. # 从答题结果中获取城市信息
  218. citys = self.marketing_db.select(self.sql_16, [uuid])
  219. if len(citys) > 0:
  220. for info in citys:
  221. city_name = info[1]
  222. if city_name in ['一线', '二线', '其他']:
  223. city = city_name
  224. else:
  225. city = '二线'
  226. # 根据用户子选项id集合,获取用户的人群分类
  227. if len(gt_75) > 0:
  228. # 特定的测试人群分类从答题结果中获取
  229. sub_option_ids = self.marketing_db.select(self.sql_17, [uuid])
  230. for option in sub_option_ids:
  231. crowd_type = self.crowd_info_1.get(option[1])
  232. if crowd_type:
  233. crowd.append(crowd_type)
  234. else:
  235. crowd.append('A')
  236. else:
  237. if sub_option_ids_1 is not None:
  238. crowd.extend(self.get_people_uuid_by_sub_option_ids(sub_option_ids_1))
  239. if city is None:
  240. city = '一线'
  241. people_info = PeopleInfo(uuid, city, nld, sex, crowd)
  242. people_infos.append(people_info)
  243. # people_infos.append([uuid, city, nld, sex, crowd])
  244. return people_infos
  245. def people_filter(self, city, nld, crowd):
  246. uuids = []
  247. for people in self.people_info_1:
  248. if people.city == city and people.age == nld and crowd in people.crowd:
  249. uuids.append(people.uuid)
  250. return uuids
  251. def get_people_uuid_by_sub_option_ids(self, sub_ids):
  252. types = []
  253. for key in self.crowd_contain_sub_option_ids.keys():
  254. type_sub_option_ids = self.crowd_contain_sub_option_ids[key]
  255. sub_option_ids = list(map(int, str(sub_ids).split(',')))
  256. # list(set(a).intersection(set(b)))
  257. if len(list(set(sub_option_ids).intersection(set(type_sub_option_ids)))) > 0 and key not in types:
  258. types.append(key)
  259. return types
  260. def update_data(self):
  261. """
  262. 定时更新分值
  263. :return:
  264. """
  265. citys = ['上海市', '杭州市', '苏州市', '无锡市', '宁波市']
  266. for city in citys:
  267. result = self.city_age_crowd(city)
  268. self.insert_score_to_db(result)
  269. print('{}数据更新完成...'.format(citys))
  270. print('{}数据关系完成...'.format(time.time()))
  271. def insert_score_to_db(self, scores):
  272. """
  273. 行为、模块分数写入数据库
  274. :return:
  275. """
  276. ids = self.query_data()
  277. behavior_score = scores['behavior_score']
  278. module_score = scores['module_score']
  279. module_insert_sql = self.get_insert_sql('模块分数')
  280. if module_insert_sql:
  281. module_insert_data = []
  282. for module in module_score:
  283. city_2 = module[0]
  284. age_2 = module[1]
  285. crowd_2 = module[2]
  286. module_name_2 = module[3]
  287. module_score_2 = module[4]
  288. for id in ids:
  289. city_1 = id[2]
  290. age_1 = id[1]
  291. crowd_1 = id[3]
  292. id_1 = id[0]
  293. if city_2 == city_1 and self.age_dict[age_2] == age_1 and crowd_2 == crowd_1:
  294. module_insert_data.append([id_1, module_name_2, module_score_2])
  295. # 先清空之前的数据
  296. table_name = self.get_table_name('模块分数')
  297. if table_name:
  298. self.shangju_db.truncate(table_name)
  299. self.shangju_db.add_some(module_insert_sql, module_insert_data)
  300. print('模块分数更新完成...')
  301. for b_score in behavior_score:
  302. for key in b_score.keys():
  303. insert_sql = self.get_insert_sql(key)
  304. if insert_sql:
  305. insert_data = []
  306. score = b_score[key]
  307. for data in score:
  308. city = data[0]
  309. age = data[1]
  310. tag_name = data[2]
  311. crowd = data[3]
  312. tag_score = data[4]
  313. for id in ids:
  314. city_1 = id[2]
  315. age_1 = id[1]
  316. crowd_1 = id[3]
  317. id_1 = id[0]
  318. if city == city_1 and self.age_dict[age] == age_1 and crowd == crowd_1:
  319. insert_data.append([id_1, tag_name, tag_score])
  320. if len(insert_data) > 0:
  321. table_name = self.get_table_name(key)
  322. if table_name:
  323. self.shangju_db.truncate(table_name)
  324. self.shangju_db.add_some(insert_sql, insert_data)
  325. else:
  326. print('未找到对应的表,数据无法插入...')
  327. print('行为分数更新完成...')
  328. def module_score(self, crowd, city, age, scores):
  329. """
  330. 模块分数计算
  331. 城市 年龄 人群分类 模块名称 分数
  332. :return:
  333. """
  334. import json
  335. print(json.dumps(scores, ensure_ascii=False))
  336. modules = self.module_scores[crowd]
  337. result = []
  338. for key in modules.keys():
  339. values = modules[key]
  340. module_name = key
  341. score = 0
  342. for value in values:
  343. behavioral_name = value[0]
  344. weight = float(value[2])
  345. standard_score = [x[4] for x in scores if x[2] == behavioral_name]
  346. if len(standard_score) > 0:
  347. score += standard_score[0] * weight
  348. result.append([city, age, crowd, module_name, score])
  349. return result
  350. # def insert_data(self, scores_behavioral, scores_module):
  351. def insert(self):
  352. """
  353. 计算数据写入数据库中,供接口查看
  354. :return:
  355. """
  356. infos = []
  357. for city in ['上海市', '宁波市', '苏州市', '杭州市', ' 无锡市']:
  358. for age in ['50-59年生', '60-69年生', '70-74年生', '75-79年生', '80-84年生', '85-89年生', '90-94年生', '95-99年生', '00'
  359. '-04年生',
  360. '05-09年生', '10-14年生', '15-19年生']:
  361. for c_type in ['A', 'B', 'C', 'D', 'E', 'F']:
  362. age_area = self.age_dict.get(age)
  363. if age_area:
  364. infos.append([age_area, city, c_type])
  365. self.shangju_db.add_some(self.sql_11, infos)
  366. def query_data(self):
  367. ids = self.shangju_db.select(self.sql_14)
  368. return ids
  369. def shanghai_85_module_score_insert(self):
  370. """
  371. 上海市,85后模块分数计算
  372. :return:
  373. """
  374. result = []
  375. for crowd in self.crowd:
  376. modules = self.module_scores[crowd]
  377. for key in modules.keys():
  378. values = modules[key]
  379. module_name = key
  380. score = 0
  381. for value in values:
  382. behavioral_name = value[0]
  383. weight = float(value[2])
  384. # standard_score = [x[4] for x in scores if x[2] == behavioral_name]
  385. standard_score = float(value[1])
  386. if standard_score is not None:
  387. score += standard_score * weight
  388. result.append(['上海市', '85后', crowd, module_name, score])
  389. return {'score': result, 'data': self.module_scores}
  390. def tag_module_score_insert(self):
  391. """
  392. 标签模块分数写入数据库
  393. :return:
  394. """
  395. ids = self.query_data()
  396. insert_data = []
  397. insert_data_1 = []
  398. for tag, module in zip(self.scores_tag, self.score_module):
  399. city = tag[0]
  400. age = tag[1]
  401. crowd = tag[2]
  402. tag_name = tag[3]
  403. tag_score = tag[4]
  404. city_2 = module[0]
  405. age_2 = module[1]
  406. crowd_2 = module[2]
  407. module_name_2 = module[3]
  408. module_score_2 = module[4]
  409. for id in ids:
  410. city_1 = id[2]
  411. age_1 = id[1]
  412. crowd_1 = id[3]
  413. id_1 = id[0]
  414. if city == city_1 and self.age_dict[age] == age_1 and crowd == crowd_1:
  415. insert_data.append([id_1, tag_name, tag_score])
  416. if city_2 == city_1 and self.age_dict[age_2] == age_1 and crowd_2 == crowd_1:
  417. insert_data_1.append([id_1, module_name_2, module_score_2])
  418. self.shangju_db.add_some(self.sql_12, insert_data)
  419. self.shangju_db.add_some(self.sql_13, insert_data_1)
  420. def init_age(self):
  421. """
  422. 获取答题数据中的年龄
  423. """
  424. age_info = self.marketing_db.select(self.sql_4)
  425. # print([x[0] for x in age_info])
  426. return [x[0] for x in age_info if x[0] is not None]
  427. def city_age_crowd(self, city=None, age=None, crowd=None):
  428. data_start = []
  429. result = []
  430. module_scores = []
  431. self.people_info_1 = self.people_info()
  432. if city is not None and age is not None and crowd is not None:
  433. print('获取指定城市,年龄段,人群类型的数据...')
  434. # people_uuids = self.get_people_uuid_by_type(crowd)
  435. people_uuids = self.people_filter(city, age, crowd)
  436. behavior_data = None
  437. if len(people_uuids) > 0:
  438. print('{}-{}-{}'.format(city, age, crowd))
  439. datas = self.behavior_tag_init(city, age, people_uuids)
  440. data_start.append(datas)
  441. all_data, behavior_data_1 = self.calculation_standard_score(datas, city, age, crowd)
  442. result.append(all_data)
  443. behavior_data = behavior_data_1
  444. if behavior_data:
  445. module_scores.extend(self.module_score(crowd, city, age, behavior_data))
  446. else:
  447. print('获取所有case的数据...')
  448. # for city in self.citys:
  449. # for city in [city]:
  450. for age in self.age:
  451. for crowd_type in self.crowd:
  452. if age == '85-89年生' and city == '上海市':
  453. print('上海市85后数据导入人工值,无需计算...')
  454. pass
  455. else:
  456. # print(' {}{}'.format(city, age))
  457. # people_uuids = self.get_people_uuid_by_type(crowd_type)
  458. people_uuids = self.people_filter(city, age, crowd)
  459. behavior_data = None
  460. if len(people_uuids) > 0:
  461. print('{}-{}-{}'.format(city, age, crowd_type))
  462. datas = self.behavior_tag_init(city, age, people_uuids)
  463. data_start.append(datas)
  464. all_data, behavior_data_1 = self.calculation_standard_score(datas, city, age, crowd_type)
  465. result.append(all_data)
  466. behavior_data = behavior_data_1
  467. if behavior_data:
  468. module_scores.extend(self.module_score(crowd_type, city, age, behavior_data))
  469. # data_list = []
  470. # for e in data_start:
  471. # for key in e.keys():
  472. # values = e[key]
  473. # for sub_e in values:
  474. # ele = [key]
  475. # ele.extend(sub_e)
  476. # data_list.append(ele)
  477. # pass
  478. return {'behavior_score': result, 'module_score': module_scores}
  479. # return {'score': result, 'data': data_list}
  480. def behavior_tag_init(self, city, age, people_uuids):
  481. result = {}
  482. self.group_type_count = self.marketing_db.select(self.sql_5, [people_uuids])
  483. # 表名
  484. for key in self.tag_data.keys():
  485. values = self.tag_data[key]
  486. result_sub = {}
  487. # 标签
  488. for key_tag_name in values.keys():
  489. questions = values[key_tag_name]
  490. elements = []
  491. for value in questions:
  492. question = value[0].split('-')[0]
  493. option = value[0].split('-')[1]
  494. corr = value[1]
  495. fz, fm = self.molecular_value(question, option, city, age, people_uuids)
  496. if fm == 0:
  497. c = 0
  498. else:
  499. c = fz / fm
  500. elements.append([question, option, corr, fz, fm, c])
  501. result_sub[key_tag_name] = elements
  502. result[key] = self.indicator_calculation_d_e(result_sub)
  503. return result
  504. def molecular_value(self, queston, option, city, age, people_uuids):
  505. # 获取当前父选项包含的子选项id和子题id列表
  506. result = self.shangju_db.select(self.sql_6, [option, queston])
  507. sub_option_ids = []
  508. group_types = []
  509. for rt in result:
  510. sub_option_id, sub_question_id, content = rt[0], rt[1], rt[2]
  511. grouptypes = self.shangju_db.select(self.sql_7, [sub_question_id])
  512. for g_t in grouptypes:
  513. if str(g_t[0]) not in group_types:
  514. group_types.append(str(g_t[0]))
  515. sub_option_ids.append(sub_option_id)
  516. # 计算子选项在答题记录中的点击数
  517. sub_options_count = 0
  518. if len(sub_option_ids) > 0:
  519. result_1 = self.marketing_db.select(self.sql_8, [sub_option_ids, people_uuids])
  520. sub_options_count = result_1[0][0]
  521. # 计算父选项包含的子选项对应的子题所在的测试gt包含的点击数。
  522. denominator_value = 0
  523. for info in self.group_type_count:
  524. if str(info[0]) in group_types:
  525. denominator_value += info[1]
  526. return sub_options_count, denominator_value
  527. def indicator_calculation_d_e(self, data):
  528. result = {}
  529. for key in data.keys():
  530. values = data[key]
  531. c_list = []
  532. for x in values:
  533. _x = x[5]
  534. if _x is not None and x != 0:
  535. c_list.append(_x)
  536. fm_list = [x[4] for x in values]
  537. sum_c = sum(fm_list)
  538. if len(c_list) == 0:
  539. min_c = 0
  540. else:
  541. min_c = min(c_list)
  542. elements = []
  543. for value in values:
  544. _value = []
  545. c = value[5]
  546. if sum_c == 0:
  547. d = 0
  548. else:
  549. d = c / sum_c
  550. e = c - min_c
  551. _value.extend(value)
  552. _value.append(d)
  553. _value.append(e)
  554. elements.append(_value)
  555. result[key] = elements
  556. return result
  557. def calculation_standard_score(self, datas, city, age, crowd_type):
  558. scores = {}
  559. for key_tag_type in datas.keys():
  560. print(key_tag_type)
  561. tag_type_data = datas[key_tag_type]
  562. scores_sub = []
  563. for key_tag in tag_type_data.keys():
  564. key_tag_data = tag_type_data[key_tag]
  565. print(key_tag)
  566. print(' 父题序号 父选项序号 相关系系数 分子值 分母值 百分比 人数权重 偏离值')
  567. values = [x[5] for x in key_tag_data]
  568. min_c = min(values)
  569. f = min_c
  570. for value in key_tag_data:
  571. print(' {}'.format(value))
  572. if value[2] is not None and value[7] is not None:
  573. f += float(value[2] * value[7])
  574. print(' 标准分:{}'.format(f))
  575. scores_sub.append([city, age, key_tag, crowd_type, f])
  576. scores[key_tag_type] = scores_sub
  577. # self.shangju_db.add_some(self.sql_9, scores)
  578. return scores, scores['用户画像-行为兴趣']
  579. def people_data(self):
  580. result = self.people_info()
  581. a = 0
  582. b = 0
  583. c = 0
  584. d = 0
  585. e = 0
  586. f = 0
  587. for rt in result:
  588. crowds = rt.crowd
  589. if 'A' in crowds:
  590. a += 1
  591. if 'B' in crowds:
  592. b += 1
  593. if 'C' in crowds:
  594. c += 1
  595. if 'D' in crowds:
  596. d += 1
  597. if 'E' in crowds:
  598. e += 1
  599. if 'F' in crowds:
  600. f += 1
  601. return {'A': a, 'B': b, 'C': b, 'D': d, 'E': e, 'F': f}
  602. def get_crowd_people(self):
  603. result = {}
  604. for type in self.crowd:
  605. uuids = self.get_people_uuid_by_type(type)
  606. result[type] = len(uuids)
  607. return result
  608. def get_people_uuid_by_type(self, type):
  609. uuids = []
  610. type_sub_option_ids = self.crowd_contain_sub_option_ids[type]
  611. for people in self.people_sub_option_ids:
  612. uuid = people[0]
  613. sub_option_ids = list(map(int, str(people[1]).split(',')))
  614. # list(set(a).intersection(set(b)))
  615. if len(list(set(sub_option_ids).intersection(set(type_sub_option_ids)))) > 0 and uuid not in uuids:
  616. uuids.append(uuid)
  617. return uuids
  618. def get_crowd_contain_sub_option_ids(self):
  619. """
  620. 获取ABCDEF人群包含的子选项id
  621. :return:
  622. """
  623. infos = {}
  624. for key in self.crowd_info.keys():
  625. values = self.crowd_info[key]
  626. sub_option_ids = []
  627. for value in values:
  628. if value is not None:
  629. vals = str(value).split('-')
  630. option, question = vals[1], vals[0]
  631. query_result = self.shangju_db.select(self.sql_6, [option, question])
  632. for qr in query_result:
  633. sub_option_id, sub_question_id, content = qr[0], qr[1], qr[2]
  634. sub_option_ids.append(int(sub_option_id))
  635. infos[key] = sub_option_ids
  636. return infos
  637. if __name__ == '__main__':
  638. mvp = Mvp()
  639. mvp.people_info()