mvp.py 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919
  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年生': '95后',
  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年生': '85后',
  20. '95-99年生': '95后'
  21. }
  22. age_list = ['85后', '95后']
  23. city_list = ['上海市', '上海周边']
  24. # 用户画像-消费结构 用户画像-生活方式
  25. tag_table = {
  26. '用户画像-审美偏好': ['mvp_crowd_info_aesthetic_preference', 'aesthetic_preference'],
  27. '用户画像-行为兴趣': ['mvp_crowd_info_behavior', 'behavioral_interest'],
  28. '用户画像-观念': ['mvp_crowd_info_consumer_concept', 'consumer_concept'],
  29. '用户画像-社交模式': ['mvp_crowd_info_social_mode', 'social_module'],
  30. '用户画像-行业': ['mvp_crowd_info_trade', 'trade'],
  31. '用户画像-出行方式': ['mvp_crowd_info_trip_mode', 'trip_mode'],
  32. '空间需求图谱-色相': ['mvp_innovate_space_color_prefer', 'color'],
  33. '空间需求图谱-精装关注点': ['mvp_innovate_space_hardcover_focus', 'hardcover_focus'],
  34. '空间需求图谱-色调': ['mvp_innovate_space_hue_prefer', 'hue'],
  35. '空间需求图谱-单品偏好': ['mvp_innovate_space_item_preference', 'item_preference'],
  36. '空间需求图谱-材质': ['mvp_innovate_space_material_prefer', 'material'],
  37. '空间需求图谱-空间特性偏好': ['mvp_innovate_space_space_prefer', 'space_preference'],
  38. '模块分数': ['mvp_crowd_info_module', 'module_name'],
  39. '用户画像-生活方式': ['mvp_crowd_info_life_style', 'life_style'],
  40. '用户画像-消费结构': ['mvp_crowd_info_consumer_structure', 'consumer_structure']
  41. }
  42. crowd_info_1 = {
  43. '1973': 'A',
  44. '1974': 'B',
  45. '1975': 'C',
  46. '1976': 'D',
  47. '1977': 'E',
  48. '1978': 'F',
  49. '1979': 'G',
  50. '1813': 'A',
  51. '1814': 'B',
  52. '1815': 'C',
  53. '1816': 'D',
  54. '1817': 'E',
  55. '1818': 'F',
  56. '1819': 'G'
  57. }
  58. base_insert_sql = '''
  59. INSERT INTO {} (
  60. crowd_info_id,
  61. {},
  62. standard_value,
  63. STATUS,
  64. creator,
  65. created
  66. )
  67. VALUES
  68. (%s, %s, %s, 1, 'binren', now())
  69. '''
  70. def get_table_name(self, name):
  71. """
  72. 获取表名
  73. :param name:
  74. :return:
  75. """
  76. params = self.tag_table.get(name)
  77. if params:
  78. return self.tag_table.get(name)[0]
  79. def get_insert_sql(self, tag_type_name):
  80. """
  81. 根据标签分类名称获取相应表的插入sql
  82. :param tag_type_name:
  83. :return:
  84. """
  85. params = self.tag_table.get(tag_type_name)
  86. if params:
  87. return self.base_insert_sql.format(params[0], params[1])
  88. crowd = ['A', 'B', 'C', 'D', 'E', 'F']
  89. # 获取答题记录中城市列表
  90. sql_1 = 'select city from f_t_daren_score_2 group by city'
  91. # 获取父选项和父题id
  92. 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 ' \
  93. 'where a.serial_number = %s and b.serial_number = %s and a.status = b.status = 1 '
  94. # 获取答题人的年龄段集合
  95. sql_4 = 'select nld from f_t_daren_score_2 group by nld'
  96. # 根据城市,年龄段,人群分类统计答题记录数
  97. sql_5 = 'select testcase_id, COUNT(DISTINCT uuid) from f_t_daren_score_2 where uuid in %s group by testcase_id '
  98. # 根据父选项获取子选项id列表
  99. sql_6 = '''
  100. SELECT
  101. c.id,
  102. c.sub_question_id,
  103. c.content
  104. FROM
  105. bq_sub_option c
  106. WHERE
  107. c.father_id IN (
  108. SELECT
  109. a.id
  110. FROM
  111. bq_option a
  112. LEFT JOIN bq_question b ON a.question_id = b.id
  113. WHERE
  114. a.serial_number = % s
  115. AND b.serial_number = % s
  116. AND a. STATUS = 1
  117. AND b. STATUS = 1
  118. )
  119. AND c. STATUS = 1
  120. '''
  121. # 根据子题id获取包含子题id的测试
  122. sql_7 = 'select id from bq_testcase where status = 1 and FIND_IN_SET(%s, question_ids)'
  123. # 根据子选项id统计答题数
  124. sql_8 = '''
  125. SELECT
  126. count(DISTINCT a.uuid)
  127. FROM
  128. f_t_daren_score_2 a
  129. LEFT JOIN d_shangju_tiku_02 b ON a.sub_question_id = b.sub_question_id
  130. AND (
  131. a.score = b.score
  132. OR a.score = b.sub_option_id
  133. )
  134. AND a.testcase_id = b.testcase_id
  135. WHERE
  136. b.sub_option_id IN % s
  137. AND a.uuid IN % s
  138. '''
  139. # 获取一个uuid下答题的子选项id列表
  140. sql_10 = 'select DISTINCT uuid, GROUP_CONCAT(DISTINCT b.sub_option_id) from f_t_daren_score_2 a left join ' \
  141. 'd_shangju_tiku_02 b on a.sub_question_id = b.sub_question_id and (a.score = b.score or a.score = ' \
  142. 'b.sub_option_id) where a.status = ' \
  143. 'b.status = 1 group by uuid '
  144. # 向表mvp_crowd_info插入数据
  145. sql_11 = 'insert into mvp_crowd_info(age_area, city_name, crowd_type, status) values(%s, %s, %s, 1)'
  146. # 向表mvp_crowd_info_behavior中插入数据
  147. sql_12 = 'insert into mvp_crowd_info_behavior(crowd_info_id, behavioral_interest, standard_value, status) values(' \
  148. '%s, %s, ' \
  149. '%s, 1) '
  150. # 向表mvp_crowd_info_module中插入数据
  151. sql_13 = 'insert into mvp_crowd_info_module(crowd_info_id, module_name, standard_value, status) values (%s, %s, ' \
  152. '%s, 1) '
  153. sql_14 = 'select a.id, a.age_area, a.city_name, a.crowd_type from mvp_crowd_info a where a.status = 1'
  154. # 获取答题城市信息from city
  155. sql_15 = '''
  156. SELECT
  157. a.uuid,
  158. IFNULL(GROUP_CONCAT(DISTINCT a.city, a.province), 00) AS city,
  159. IFNULL(GROUP_CONCAT(DISTINCT a.nld), 00) AS nld,
  160. IFNULL(GROUP_CONCAT(DISTINCT a.sex), 00) AS sex,
  161. IFNULL(GROUP_CONCAT(DISTINCT b.sub_option_id), 00) as sub_option_ids,
  162. IFNULL(GROUP_CONCAT(DISTINCT a.testcase_id), 00) as testcase_ids
  163. FROM
  164. f_t_daren_score_2 a
  165. LEFT JOIN d_shangju_tiku_02 b ON a.testcase_id = b.testcase_id
  166. WHERE
  167. a.testcase_id = b.testcase_id
  168. AND a.sub_question_id = b.sub_question_id
  169. AND (
  170. a.score = b.score
  171. OR a.score = b.sub_option_id
  172. )
  173. GROUP BY
  174. a.uuid
  175. '''
  176. # 根据用户uuid获取城市信息
  177. sql_16 = '''
  178. SELECT
  179. a.uuid,
  180. b.sub_option_content
  181. FROM
  182. f_t_daren_score_2 a
  183. LEFT JOIN d_shangju_tiku_02 b ON a.testcase_id = b.testcase_id
  184. WHERE
  185. a.sub_question_id = b.sub_question_id
  186. AND (
  187. a.score = b.score
  188. OR a.score = b.sub_option_id
  189. )
  190. AND a.uuid = %s
  191. AND b.father_id = 249
  192. AND a. STATUS = b. STATUS = 1
  193. '''
  194. # 答题人人群分类信息
  195. sql_17 = '''
  196. SELECT
  197. a.uuid,
  198. b.sub_option_id
  199. FROM
  200. f_t_daren_score_2 a
  201. LEFT JOIN d_shangju_tiku_02 b ON a.testcase_id = b.testcase_id
  202. WHERE
  203. a.sub_question_id = b.sub_question_id
  204. AND (
  205. a.score = b.score
  206. OR a.score = b.sub_option_id
  207. )
  208. AND a.uuid = %s
  209. AND b.father_id = 236
  210. AND a.STATUS = b.STATUS = 1
  211. '''
  212. sql_18 = '''
  213. DELETE
  214. FROM
  215. mvp_crowd_info_behavior
  216. WHERE
  217. crowd_info_id not IN (
  218. SELECT
  219. GROUP_CONCAT(id)
  220. FROM
  221. mvp_crowd_info
  222. WHERE
  223. city_name = '上海市'
  224. AND age_area = '85后'
  225. AND STATUS = 1
  226. )
  227. '''
  228. # 根据名称获取图标
  229. sql_19 = '''
  230. SELECT
  231. id,
  232. NAME
  233. FROM
  234. mvp_icon
  235. WHERE status = 1
  236. '''
  237. # 行为更新图标
  238. sql_20 = '''
  239. UPDATE mvp_crowd_info_behavior
  240. SET icon_id = % s
  241. WHERE
  242. behavioral_interest = % s
  243. '''
  244. # 模块图标更新
  245. sql_21 = '''
  246. '''
  247. # 更新性别占比数据
  248. sql_22 = '''
  249. INSERT INTO mvp_crowd_info_gender_rate (
  250. crowd_info_id,
  251. gender,
  252. standard_value,
  253. status,
  254. creator,
  255. created
  256. )
  257. VALUES
  258. (%s, %s, %s, 1, 'binren', now())
  259. '''
  260. """
  261. 数据debug SQL
  262. 1:
  263. SELECT
  264. c.id,
  265. c.sub_question_id,
  266. c.content
  267. FROM
  268. bq_sub_option c
  269. WHERE
  270. c.father_id IN (
  271. SELECT
  272. a.id
  273. FROM
  274. bq_option a
  275. LEFT JOIN bq_question b ON a.question_id = b.id
  276. WHERE
  277. a.serial_number ='FA001'
  278. AND b.serial_number = 'F00245'
  279. AND a. STATUS = 1
  280. AND b. STATUS = 1
  281. )
  282. AND c.STATUS = 1
  283. 2:
  284. select id from bq_testcase where status = 1 and FIND_IN_SET(%s, question_ids)
  285. 3:
  286. SELECT
  287. count(1)
  288. FROM
  289. f_t_daren_score_2 a
  290. LEFT JOIN d_shangju_tiku_02 b ON a.sub_question_id = b.sub_question_id
  291. AND (
  292. a.score = b.score
  293. OR a.score = b.sub_option_id
  294. )
  295. AND a.testcase_id = b.testcase_id
  296. WHERE
  297. b.sub_option_id IN (1964,1965,1966,1967,1968,1969,1970,1971,1972)
  298. """
  299. def __init__(self, path=None):
  300. self.shangju_db = MysqlDB('shangju')
  301. self.marketing_db = MysqlDB('bi_report')
  302. self.linshi_db = MysqlDB('linshi', db_type=1)
  303. # self.shangju_db.truncate('mvp_standard_score')
  304. self.tag_data = ExcelUtil(file_name=path).init_mvp_data()
  305. self.crowd_info = ExcelUtil(file_name=path, sheet_name='选项-人群分类对应表').init_crowd_info()
  306. self.citys = self.init_city()
  307. self.age = self.init_age()
  308. self.people_sub_option_ids = self.marketing_db.select(self.sql_10)
  309. self.crowd_contain_sub_option_ids = self.get_crowd_contain_sub_option_ids()
  310. self.module_scores = ExcelUtil(file_name='set-behavior-tag.xlsx', sheet_name='算法关系表').init_module_info()
  311. # self.scores_tag = ExcelUtil(file_name='行为与模块分值汇总.xlsx', sheet_name='行为').init_scores()
  312. # self.score_module = ExcelUtil(file_name='行为与模块分值汇总.xlsx', sheet_name='模块').init_scores()
  313. self.scores_tag = None
  314. self.score_module = None
  315. self.people_info_1 = self.people_info()
  316. def close(self):
  317. self.shangju_db.close()
  318. self.marketing_db.close()
  319. self.linshi_db.close()
  320. def init_city(self):
  321. """
  322. 获取答题数据中的城市。
  323. :return:
  324. """
  325. citys = ['上海市', '上海周边']
  326. # citys_info = self.marketing_db.select(self.sql_1)
  327. # citys.extend([x[0] for x in citys_info if x[0] is not None])
  328. return citys
  329. def query_behavioral_info(self, city=None, age=None, crowd=None):
  330. """
  331. 查询行为兴趣信息
  332. :return:
  333. """
  334. # datas = []
  335. # for key in self.tag_data.keys():
  336. # values = self.tag_data[key]
  337. # for value in values:
  338. # question = value[0].split('-')[0]
  339. # option = value[0].split('-')[1]
  340. # corr = value[1]
  341. # data = self.shangju_db.select(self.sql_2, [option, question])
  342. # if len(data) > 0:
  343. # print([question, option, data[0][3], data[0][1], key, corr])
  344. # datas.append([question, option, data[0][3], data[0][1], key, corr])
  345. # self.shangju_db.truncate('mvp_question_classification')
  346. # self.shangju_db.add_some(self.sql_3, datas)
  347. scores_behavioral = self.city_age_crowd(city, age, crowd)
  348. # scores_module = self.module_score(crowd, city, age, scores_behavioral['score'])
  349. # result = {'行为兴趣分值': scores_behavioral['score'], '模块分值': scores_module}
  350. print('update finished!!!')
  351. return scores_behavioral
  352. def people_info(self):
  353. """
  354. 答题人个人信息获取
  355. :return:
  356. """
  357. people_info_city = self.marketing_db.select(self.sql_15)
  358. people_infos = []
  359. for people in people_info_city:
  360. uuid = people[0]
  361. city = people[1]
  362. nld = people[2]
  363. sex = people[3]
  364. if sex and len(str(sex).split(',')) > 0:
  365. sex = str(sex).split(',')[0]
  366. else:
  367. sex = '3'
  368. sub_option_ids_1 = people[4]
  369. testcaseid = people[5]
  370. if str(city).find('市') != -1:
  371. city = str(city).split('市')[0] + '市'
  372. if str(nld).find(',') != -1:
  373. nld_1 = list(str(nld).split(','))
  374. if len(nld_1) > 0:
  375. nld = nld_1[0]
  376. else:
  377. pass
  378. crowd = []
  379. if testcaseid:
  380. testcastids = list(map(int, str(testcaseid).split(',')))
  381. if len(testcastids) > 0:
  382. gt_75 = [x for x in testcastids if x > 74]
  383. if len(gt_75) > 0:
  384. # 从答题结果中获取城市信息
  385. citys = self.marketing_db.select(self.sql_16, [uuid])
  386. if len(citys) > 0:
  387. city = '上海市' if citys[0][1] == '一线' else '上海周边'
  388. # 根据用户子选项id集合,获取用户的人群分类
  389. if len(gt_75) > 0:
  390. # 特定的测试人群分类从答题结果中获取
  391. sub_option_ids = self.marketing_db.select(self.sql_17, [uuid])
  392. for option in sub_option_ids:
  393. crowd_type = self.crowd_info_1.get(option[1])
  394. if crowd_type:
  395. crowd.append(crowd_type)
  396. else:
  397. crowd.append('A')
  398. else:
  399. if sub_option_ids_1 is not None:
  400. crowd.extend(self.get_people_uuid_by_sub_option_ids(sub_option_ids_1))
  401. if city is None:
  402. city = '上海市'
  403. people_info = PeopleInfo(uuid, city, nld, sex, crowd)
  404. people_infos.append(people_info)
  405. # people_infos.append([uuid, city, nld, sex, crowd])
  406. return people_infos
  407. def people_filter(self, city, nld, crowd):
  408. uuids = []
  409. for people in self.people_info_1:
  410. if people.city == city and people.age == nld and crowd in people.crowd:
  411. uuids.append(people.uuid)
  412. return uuids
  413. def get_people_uuid_by_sub_option_ids(self, sub_ids):
  414. types = []
  415. for key in self.crowd_contain_sub_option_ids.keys():
  416. type_sub_option_ids = self.crowd_contain_sub_option_ids[key]
  417. sub_option_ids = list(map(int, str(sub_ids).split(',')))
  418. # list(set(a).intersection(set(b)))
  419. if len(list(set(sub_option_ids).intersection(set(type_sub_option_ids)))) > 0 and key not in types:
  420. types.append(key)
  421. return types
  422. def update_data(self):
  423. """
  424. 定时更新分值
  425. 使用真实数据模块名称:用户画像-行为兴趣,空间需求图谱-材质,空间需求图谱-色调,空间需求图谱-色相
  426. 用户画像-行业,用户画像-出行方式,用户画像-消费结构,用户画像-生活方式,用户画像-社交模式, 模块分数
  427. :return:
  428. """
  429. self.insert_table = []
  430. self.ids = self.query_data()
  431. for city in self.city_list:
  432. for age in self.age_list:
  433. for crowd in self.crowd:
  434. result = self.city_age_crowd(city, age, crowd)
  435. self.insert_score_to_db(result)
  436. print('{}数据更新完成...'.format(time.time()))
  437. self.update_gender_rate()
  438. self.update_icon()
  439. def update_gender_rate(self, ids=None):
  440. """
  441. 更新性别占比
  442. :return:
  443. """
  444. if ids:
  445. self.ids = self.query_data()
  446. insert_data = []
  447. for city in self.city_list:
  448. for age in self.age_list:
  449. for crowd in self.crowd:
  450. boy = 0
  451. girl = 0
  452. for people in self.people_info_1:
  453. if people.sex is not None and city == people.city and crowd in people.crowd and age == people.age:
  454. if people.sex == '1':
  455. boy += 1
  456. if people.sex == '2':
  457. girl += 1
  458. crowd_info_id = self.get_crowd_info_id([city, age, crowd])
  459. if crowd_info_id and (boy + girl) > 0:
  460. boy_rate = boy / (boy + girl)
  461. insert_data.append([crowd_info_id, 1, boy_rate])
  462. girl_rate = girl / (boy + girl)
  463. insert_data.append([crowd_info_id, 0, girl_rate])
  464. if len(insert_data) > 0:
  465. self.linshi_db.truncate('mvp_crowd_info_gender_rate')
  466. self.linshi_db.add_some(self.sql_22, insert_data)
  467. print('性别占比更新完成...')
  468. else:
  469. print('无数据更新...')
  470. def get_crowd_info_id(self, people_info):
  471. for id_data in self.ids:
  472. city_1 = id_data[2]
  473. age_1 = id_data[1]
  474. crowd_1 = id_data[3]
  475. id_1 = id_data[0]
  476. if people_info[0] == city_1 and people_info[1] == age_1 and people_info[2] == crowd_1:
  477. return id_1
  478. def update_image(self):
  479. """
  480. 更新标签关联的图片信息
  481. :return:
  482. """
  483. pass
  484. def update_icon(self):
  485. """
  486. 标签关联图标
  487. :return:
  488. """
  489. icons = self.linshi_db.select(self.sql_19)
  490. for ic in icons:
  491. id = ic[0]
  492. name = ic[1]
  493. self.linshi_db.update(self.sql_20, [id, name])
  494. print('行为标签关联图标完成...')
  495. def insert_score_to_db(self, scores):
  496. """
  497. 行为、模块分数写入数据库
  498. :return:
  499. """
  500. behavior_score = scores['behavior_score']
  501. module_score = scores['module_score']
  502. module_insert_sql = self.get_insert_sql('模块分数')
  503. if module_insert_sql:
  504. module_insert_data = []
  505. for module in module_score:
  506. data = self.need_inert(module)
  507. if data:
  508. module_insert_data.append(data)
  509. # 先清空之前的数据
  510. if len(module_insert_data) > 0:
  511. table_name = self.get_table_name('模块分数')
  512. if table_name is not None and table_name not in self.insert_table:
  513. self.linshi_db.truncate(table_name)
  514. self.linshi_db.add_some(module_insert_sql, module_insert_data)
  515. self.insert_table.append(table_name)
  516. print('模块分数更新完成...')
  517. for b_score in behavior_score:
  518. for key in b_score.keys():
  519. insert_sql = self.get_insert_sql(key)
  520. if insert_sql:
  521. insert_data = []
  522. score = b_score[key]
  523. for data in score:
  524. insert_data_element = self.need_inert(data)
  525. if insert_data_element:
  526. insert_data.append(insert_data_element)
  527. if len(insert_data) > 0:
  528. table_name = self.get_table_name(key)
  529. if table_name and table_name not in self.insert_table:
  530. # if table_name == 'mvp_crowd_info_behavior':
  531. # self.linshi_db.delete(self.sql_18)
  532. # else:
  533. self.linshi_db.truncate(table_name)
  534. self.linshi_db.add_some(insert_sql, insert_data)
  535. self.insert_table.append(table_name)
  536. else:
  537. print('未找到对应的表,数据无法插入...')
  538. print('行为分数更新完成...')
  539. def need_inert(self, data):
  540. city = data[0]
  541. age = data[1]
  542. crowd = data[2]
  543. tag_name = data[3]
  544. tag_score = data[4]
  545. # if key == '用户画像-行为兴趣' and city == '上海市' and age == '85后':
  546. # pass
  547. # else:
  548. for id_data in self.ids:
  549. city_1 = id_data[2]
  550. age_1 = id_data[1]
  551. crowd_1 = id_data[3]
  552. id_1 = id_data[0]
  553. if city == city_1 and age == age_1 and crowd == crowd_1:
  554. return [id_1, tag_name, tag_score]
  555. def module_score(self, crowd, city, age, scores):
  556. """
  557. 模块分数计算
  558. 城市 年龄 人群分类 模块名称 分数
  559. :return:
  560. """
  561. # import json
  562. # print(json.dumps(scores, ensure_ascii=False))
  563. modules = self.module_scores[crowd]
  564. result = []
  565. for key in modules.keys():
  566. values = modules[key]
  567. module_name = key
  568. score = 0
  569. for value in values:
  570. behavioral_name = value[0]
  571. weight = float(value[2])
  572. standard_score = [x[4] for x in scores if x[3] == behavioral_name]
  573. if len(standard_score) > 0:
  574. score += standard_score[0] * weight
  575. result.append([city, age, crowd, module_name, score])
  576. return result
  577. # def insert_data(self, scores_behavioral, scores_module):
  578. def insert(self):
  579. """
  580. 计算数据写入数据库中,供接口查看
  581. :return:
  582. """
  583. infos = []
  584. for city in self.city_list:
  585. for age in self.age_list:
  586. for c_type in self.crowd:
  587. age_area = self.age_dict.get(age)
  588. if age_area:
  589. infos.append([age_area, city, c_type])
  590. self.shangju_db.add_some(self.sql_11, infos)
  591. def query_data(self):
  592. ids = self.linshi_db.select(self.sql_14)
  593. return ids
  594. def shanghai_85_module_score_insert(self):
  595. """
  596. 上海市,85后模块分数计算
  597. :return:
  598. """
  599. result = []
  600. for crowd in self.crowd:
  601. modules = self.module_scores[crowd]
  602. for key in modules.keys():
  603. values = modules[key]
  604. module_name = key
  605. score = 0
  606. for value in values:
  607. behavioral_name = value[0]
  608. weight = float(value[2])
  609. # standard_score = [x[4] for x in scores if x[2] == behavioral_name]
  610. standard_score = float(value[1])
  611. if standard_score is not None:
  612. score += standard_score * weight
  613. result.append(['上海市', '85后', crowd, module_name, score])
  614. return {'score': result, 'data': self.module_scores}
  615. def tag_module_score_insert(self):
  616. """
  617. 标签模块分数写入数据库
  618. :return:
  619. """
  620. ids = self.query_data()
  621. insert_data = []
  622. insert_data_1 = []
  623. for tag, module in zip(self.scores_tag, self.score_module):
  624. city = tag[0]
  625. age = tag[1]
  626. crowd = tag[2]
  627. tag_name = tag[3]
  628. tag_score = tag[4]
  629. city_2 = module[0]
  630. age_2 = module[1]
  631. crowd_2 = module[2]
  632. module_name_2 = module[3]
  633. module_score_2 = module[4]
  634. for id in ids:
  635. city_1 = id[2]
  636. age_1 = id[1]
  637. crowd_1 = id[3]
  638. id_1 = id[0]
  639. if city == city_1 and self.age_dict[age] == age_1 and crowd == crowd_1:
  640. insert_data.append([id_1, tag_name, tag_score])
  641. if city_2 == city_1 and self.age_dict[age_2] == age_1 and crowd_2 == crowd_1:
  642. insert_data_1.append([id_1, module_name_2, module_score_2])
  643. self.shangju_db.add_some(self.sql_12, insert_data)
  644. self.shangju_db.add_some(self.sql_13, insert_data_1)
  645. def init_age(self):
  646. """
  647. 获取答题数据中的年龄
  648. """
  649. return ['95后', '85后']
  650. # age_info = self.marketing_db.select(self.sql_4)
  651. # # print([x[0] for x in age_info])
  652. # return [x[0] for x in age_info if x[0] is not None]
  653. def city_age_crowd(self, city=None, age=None, crowd=None):
  654. data_start = []
  655. result = []
  656. module_scores = []
  657. if city is not None and age is not None and crowd is not None:
  658. print('获取指定城市,年龄段,人群类型的数据...')
  659. # people_uuids = self.get_people_uuid_by_type(crowd)
  660. people_uuids = self.people_filter(city, age, crowd)
  661. behavior_data = None
  662. if len(people_uuids) > 0:
  663. print('{}-{}-{}'.format(city, age, crowd))
  664. datas = self.behavior_tag_init(city, age, people_uuids)
  665. data_start.append(datas)
  666. all_data, behavior_data_1 = self.calculation_standard_score(datas, city, age, crowd)
  667. result.append(all_data)
  668. behavior_data = behavior_data_1
  669. if behavior_data:
  670. module_scores.extend(self.module_score(crowd, city, age, behavior_data))
  671. # data_list = []
  672. # for e in data_start:
  673. # for key in e.keys():
  674. # values = e[key]
  675. # for sub_e in values:
  676. # ele = [key]
  677. # ele.extend(sub_e)
  678. # data_list.append(ele)
  679. # pass
  680. return {'behavior_score': result, 'module_score': module_scores}
  681. # return {'score': result, 'data': data_list}
  682. def scores(self):
  683. behavior_score = []
  684. module_scores = []
  685. for city in self.city_list:
  686. for age in self.age_list:
  687. for crowd in self.crowd:
  688. data = self.city_age_crowd(city, age, crowd)
  689. behavior_score.extend(data['behavior_score'])
  690. module_scores.extend(data['module_score'])
  691. return {'behavior_score': behavior_score, 'module_score': module_scores}
  692. def behavior_tag_init(self, city, age, people_uuids):
  693. result = {}
  694. self.group_type_count = self.marketing_db.select(self.sql_5, [people_uuids])
  695. # 表名
  696. for key in self.tag_data.keys():
  697. values = self.tag_data[key]
  698. result_sub = {}
  699. # 标签
  700. for key_tag_name in values.keys():
  701. questions = values[key_tag_name]
  702. elements = []
  703. for value in questions:
  704. question = value[0].split('-')[0]
  705. option = value[0].split('-')[1]
  706. corr = value[1]
  707. fz, fm = self.molecular_value(question, option, city, age, people_uuids)
  708. if fm == 0:
  709. c = 0
  710. else:
  711. c = fz / fm
  712. elements.append([question, option, corr, fz, fm, c])
  713. result_sub[key_tag_name] = elements
  714. result[key] = self.indicator_calculation_d_e(result_sub)
  715. return result
  716. def molecular_value(self, queston, option, city, age, people_uuids):
  717. # 获取当前父选项包含的子选项id和子题id列表
  718. result = self.shangju_db.select(self.sql_6, [option, queston])
  719. sub_option_ids = []
  720. group_types = []
  721. for rt in result:
  722. sub_option_id, sub_question_id, content = rt[0], rt[1], rt[2]
  723. grouptypes = self.shangju_db.select(self.sql_7, [sub_question_id])
  724. for g_t in grouptypes:
  725. if str(g_t[0]) not in group_types:
  726. group_types.append(str(g_t[0]))
  727. sub_option_ids.append(sub_option_id)
  728. # 计算子选项在答题记录中的点击数
  729. sub_options_count = 0
  730. if len(sub_option_ids) > 0:
  731. result_1 = self.marketing_db.select(self.sql_8, [sub_option_ids, people_uuids])
  732. sub_options_count = result_1[0][0]
  733. # 计算父选项包含的子选项对应的子题所在的测试gt包含的点击数。
  734. denominator_value = 0
  735. for info in self.group_type_count:
  736. if str(info[0]) in group_types:
  737. denominator_value += info[1]
  738. return sub_options_count, denominator_value
  739. def indicator_calculation_d_e(self, data):
  740. result = {}
  741. for key in data.keys():
  742. values = data[key]
  743. c_list = []
  744. for x in values:
  745. _x = x[5]
  746. if _x is not None and x != 0:
  747. c_list.append(_x)
  748. fm_list = [x[4] for x in values]
  749. sum_c = sum(fm_list)
  750. if len(c_list) == 0:
  751. min_c = 0
  752. else:
  753. min_c = min(c_list)
  754. elements = []
  755. for value in values:
  756. _value = []
  757. c = value[5]
  758. if sum_c == 0:
  759. d = 0
  760. else:
  761. d = c / sum_c
  762. e = c - min_c
  763. _value.extend(value)
  764. _value.append(d)
  765. _value.append(e)
  766. elements.append(_value)
  767. result[key] = elements
  768. return result
  769. def calculation_standard_score(self, datas, city, age, crowd_type):
  770. scores = {}
  771. for key_tag_type in datas.keys():
  772. print(key_tag_type)
  773. tag_type_data = datas[key_tag_type]
  774. scores_sub = []
  775. for key_tag in tag_type_data.keys():
  776. key_tag_data = tag_type_data[key_tag]
  777. print(key_tag)
  778. print(' 父题序号 父选项序号 相关系系数 分子值 分母值 百分比 人数权重 偏离值')
  779. values = [x[5] for x in key_tag_data]
  780. min_c = min(values)
  781. f = min_c
  782. for value in key_tag_data:
  783. print(' {}'.format(value))
  784. if value[2] is not None and value[7] is not None:
  785. f += float(value[2] * value[7])
  786. print(' 标准分:{}'.format(f))
  787. scores_sub.append([city, age, crowd_type, key_tag, f])
  788. scores[key_tag_type] = scores_sub
  789. # self.shangju_db.add_some(self.sql_9, scores)
  790. return scores, scores['用户画像-行为兴趣']
  791. def people_data(self):
  792. result = self.people_info()
  793. a = 0
  794. b = 0
  795. c = 0
  796. d = 0
  797. e = 0
  798. f = 0
  799. for rt in result:
  800. crowds = rt.crowd
  801. if 'A' in crowds:
  802. a += 1
  803. if 'B' in crowds:
  804. b += 1
  805. if 'C' in crowds:
  806. c += 1
  807. if 'D' in crowds:
  808. d += 1
  809. if 'E' in crowds:
  810. e += 1
  811. if 'F' in crowds:
  812. f += 1
  813. return {'A': a, 'B': b, 'C': b, 'D': d, 'E': e, 'F': f}
  814. def get_crowd_people(self):
  815. result = {}
  816. for type in self.crowd:
  817. uuids = self.get_people_uuid_by_type(type)
  818. result[type] = len(uuids)
  819. return result
  820. def get_people_uuid_by_type(self, type):
  821. uuids = []
  822. type_sub_option_ids = self.crowd_contain_sub_option_ids[type]
  823. for people in self.people_sub_option_ids:
  824. uuid = people[0]
  825. sub_option_ids = list(map(int, str(people[1]).split(',')))
  826. # list(set(a).intersection(set(b)))
  827. if len(list(set(sub_option_ids).intersection(set(type_sub_option_ids)))) > 0 and uuid not in uuids:
  828. uuids.append(uuid)
  829. return uuids
  830. def get_crowd_contain_sub_option_ids(self):
  831. """
  832. 获取ABCDEF人群包含的子选项id
  833. :return:
  834. """
  835. infos = {}
  836. for key in self.crowd_info.keys():
  837. values = self.crowd_info[key]
  838. sub_option_ids = []
  839. for value in values:
  840. if value is not None:
  841. vals = str(value).split('-')
  842. option, question = vals[1], vals[0]
  843. query_result = self.shangju_db.select(self.sql_6, [option, question])
  844. for qr in query_result:
  845. sub_option_id, sub_question_id, content = qr[0], qr[1], qr[2]
  846. sub_option_ids.append(int(sub_option_id))
  847. infos[key] = sub_option_ids
  848. return infos
  849. if __name__ == '__main__':
  850. pass