stems_structure.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393
  1. #!/usr/bin/env/python
  2. # -*- coding:utf-8 -*-
  3. import re
  4. from utils.item_type_line import get_item_head_info
  5. from utils.topic_no import judge_item_no_type, get_right_no, pre_get_item_no
  6. def stems_structure_byno(stem_con, subject=""):
  7. """
  8. 按题号进行切分;
  9. 针对无解析的试卷中所有题目的拆分;
  10. :return:{"stem": , "item_id": , "errmsgs": [],"type":,}
  11. """
  12. head_cons = []
  13. try:
  14. while stem_con and ((re.search(r"[\u4e00-\u9fa5]", stem_con[0]) is None) or
  15. (re.search(r"[一二三四]\s*[、..、]\s*[^必考基础综合中等]{2,4}题", stem_con[0]) is None
  16. and re.search(r"(^|\n)\s*[1-4][0-9]?\s*[..、、]((?!(答题卡|涂黑|本卷|2B铅笔|签字笔|密封线)).)*?$",
  17. stem_con[0]) is None)):
  18. head_cons.append(stem_con[0])
  19. del stem_con[0]
  20. except:
  21. return "本份试卷开头格式有问题,请按试卷格式来!"
  22. stem_str = "\n" + "\n".join(stem_con)
  23. # 题号格式有条件清洗
  24. # def sub1(ss):
  25. # if int(ss.group(5)) - int(ss.group(2)) in [1, 2]:
  26. # return ss.group(1)+"\n"+ss.group(5)+"、"+ss.group(6)
  27. # else:
  28. # return ss.group(0)
  29. # stem_str = re.sub(r"(\n\s*([1-4][0-9]|[1-9])\s*[..、、]((?!\n\s*([1-4][0-9]|[1-9])\s*[..、、]).)+?)\n+\s*([1-4][0-9]|[1-9])\s*(?![..、、])([^\s\d]+)", sub1, stem_str, flags=re.S)
  30. # 也可以用下面方法,但比较啰嗦
  31. while re.search(r"(\n\s*([1-4][0-9]|[1-9])\s*[..、、]((?!\n\s*([1-4][0-9]|[1-9])\s*[..、、]).)+?)\n+\s*([1-4][0-9]|[1-9])\s*(?![..、、])([^\s\d]+)", stem_str, re.S):
  32. wrong_id_info = re.search(r"(\n\s*([1-4][0-9]|[1-9])\s*[..、、]((?!\n\s*([1-4][0-9]|[1-9])\s*[..、、]).)+?)\n+\s*([1-4][0-9]|[1-9])\s*(?![..、、])([^\s\d]+)", stem_str, re.S)
  33. stem_str = stem_str.replace(wrong_id_info.group(0), wrong_id_info.group(1)+"\n"+wrong_id_info.group(5)+"、"+wrong_id_info.group(6))
  34. # print(stem_str)
  35. # 1、获取题型行信息、按题型行切分
  36. con11, title_info_dict, choice_class = get_item_head_info(stem_str)
  37. all_type = title_info_dict["all_type"]
  38. title_type_num = title_info_dict["title_type_num"]
  39. select_type_id = title_info_dict["select_type_id"]
  40. each_item_score, each_item_score2 = title_info_dict["each_item_score"], title_info_dict["each_item_score2"]
  41. # -------------------------------------------------------
  42. res = []
  43. item_type_classify = {} # 记录每类题型中含有的题目个数,含合并的情况
  44. item_type_num = [] # 题型不合并
  45. pic_no = {} # 记录每个题的图
  46. new_item_no = [] # 将纠错后的题号再记录一份
  47. item_groups = {"is_groups": 0, "groups_data": {}} # 公共题干的位置,从哪个题开始,比如地理选择题
  48. if not all_type:
  49. print("不存在大题题型行或题型行格式或名称有问题")
  50. # 初步获取题号,题号类型
  51. stem_str, item_no_info, item_no_type = judge_item_no_type(stem_str)
  52. # 获取正确题号的位置,进行切分
  53. new_item_no, items_no_idx = get_right_no(item_no_info)
  54. one_item_split = [stem_str[i:j] for i, j in zip(items_no_idx, items_no_idx[1:] + [None])]
  55. dd = {}
  56. for n, one_item in enumerate(one_item_split):
  57. if subject == "地理" :
  58. res, com_stem, item_groups = split_with_comstem(head_cons, one_item_split, res, n, item_groups)
  59. if com_stem:
  60. dd.update(com_stem)
  61. # if not n:
  62. # mix_con = "\n".join(head_cons).strip()
  63. # else:
  64. # mix_con = one_item_split[n - 1].strip()
  65. # pattern_3 = re.search("(完成|回答)下?[面列]?的?.*?[\d小]题.{,2}$", mix_con)
  66. # if pattern_3:
  67. # com_stem, bef_con = "", ""
  68. # if re.search("【题文】", mix_con):
  69. # bef_con, com_stem = mix_con.split("【题文】", maxsplit=1)
  70. # else:
  71. # com_stem_idx = [i.end() for i in re.finditer(r"(所以|故而?).{,3}(选择?[A-Fa-f]选?项?"
  72. # r"|选项[A-Fa-f]正确).{,2}\n"
  73. # r"|\n[A-E]\s*[..、、::].*?\n", mix_con)]
  74. # if com_stem_idx:
  75. # com_stem = mix_con[com_stem_idx[-1]+1:]
  76. # bef_con = mix_con[:com_stem_idx[-1]+1]
  77. # else:
  78. # if not n:
  79. # com_stem = mix_con
  80. # else:
  81. # mix_con_list = mix_con.split(r"(详解】|解析】|答案】)")
  82. # if len(mix_con_list) > 2:
  83. # bef_con = "".join(bef_con[:-1])
  84. # mix_con = bef_con[-1]
  85. # else:
  86. # mix_con = bef_con[0]
  87. # paras = bef_con.split("\n")
  88. # paras = [para for para in paras if para.strip()]
  89. # if len(paras)>1:
  90. # if len(paras) == 2 or len(paras[-1]) >= 20:
  91. # com_stem = paras[-1]
  92. # bef_con = bef_con + "\n".join(paras[:-1])
  93. # else:
  94. # com_stem = paras[-2:]
  95. # bef_con = bef_con + "\n".join(paras[:-2])
  96. # else:
  97. # bef_con = bef_con + "\n".join(paras)
  98. # dd["com_stem"] = com_stem
  99. # res[-1]["stem"] = bef_con
  100. dd["stem"] = one_item
  101. dd["item_id"] = new_item_no[n] # 题目本身的题号
  102. dd["type"] = "" # 先题型不备注,根据答案再看
  103. dd["errmsgs"] = []
  104. dd["score"] = 0
  105. # if select_type_id and dd["item_id"] in select_type_id:
  106. # dd['is_optional'] = 'true'
  107. res.append(dd)
  108. dd = {}
  109. # 先不做拆图处理了
  110. else:
  111. # print(all_type, len(con11))
  112. if len(all_type) == len(con11)-1: # 第一部分的题型行掉了
  113. all_type.insert(0, "")
  114. each_item_score.insert(0, 0) # 按题型行拿的分数也会掉,先补上默认的0
  115. elif len(all_type) != len(con11):
  116. print("第二种试卷格式:存在题型行没有换行") # 可能造成题目和题型行在同一行
  117. # return "存在题型行末尾没有换行或题型行中题型不明确"
  118. # else:
  119. # # print(all_type)
  120. # if "非选择题" in all_type:
  121. # error_info1 = "第" + str(all_type.index("非选择题")+1) + "大题的题型不明确"
  122. # if any([True for one_type in all_type if re.search("必考基础综合中等面列下各", one_type)]):
  123. # error_info1 = "存在题型行中题型不明确"
  124. # ---------------------------------------------------------------------
  125. # 思路:>>>>先纠正题号,再拆分题目;等切分好后再纠正(删减添加操作)比较费时
  126. # 按题号切分,可再加些细节!!!! 1>>题号不要求连续
  127. # 初步判断题号类型
  128. stem_str, item_no_info, item_no_type = judge_item_no_type(stem_str)
  129. # >>>>切分题目
  130. for num, one_type in enumerate(con11):
  131. # 初步获取题号
  132. item_no_info = pre_get_item_no("\n"+one_type, item_no_type)
  133. # 获取正确题号的位置,进行切分
  134. if res:
  135. items_no_temp, items_no_idx = get_right_no(item_no_info, have_type=1, last_id=res[-1]["item_id"])
  136. else:
  137. items_no_temp, items_no_idx = get_right_no(item_no_info)
  138. is_from_0 = 1
  139. if items_no_temp and items_no_idx[0] != 0 and items_no_temp[0] > 1: # 以防出现题号漏了的情况
  140. items_no_idx.insert(0, 0)
  141. is_from_0 = 0
  142. one_item_split = [("\n" + one_type)[i:j] for i, j in zip(items_no_idx, items_no_idx[1:] + [None])]
  143. # 针对多个题共用一段材料的情况2021-11-3
  144. head_item = one_type[0:items_no_idx[0]]
  145. # if head_item and subject == "地理":
  146. # res, com_stem, item_group = split_with_comstem(head_item, [], res, 0)
  147. # item_groups.update(item_group)
  148. # if com_stem:
  149. # dd["com_stem"] = com_stem
  150. # common_stem_may = re.search("(完成|回答)下?[面列]?的?第?(\d{1,2})[-到至第~~-]+?(\d{1,2})题", head_item.replace(" ", ""))
  151. # if common_stem_may:
  152. # if not item_groups:
  153. # item_groups["pos"].append(1)
  154. # else:
  155. # item_groups["pos"].append(len(res)+1)
  156. # item_groups["{}-{}".format(common_stem_may.group(2), common_stem_may.group(3))] = head_item
  157. # ------------------每个大题的第一题前面的图可能有漏的情况------------------------
  158. may_oimt_pic = []
  159. if not is_from_0:
  160. may_oimt_pic_info = re.search("\n(<imgsrc.+?/>(\s*<imgsrc.+?/>)*?)\s*\n?$", one_item_split[0])
  161. if may_oimt_pic_info:
  162. if len(one_item_split) > 1 and re.search("如[上下左右]?图", one_item_split[1]):
  163. may_oimt_pic.extend(re.findall("<imgsrc.+?/>", may_oimt_pic_info.group(1)))
  164. # print("may_oimt_pic:", may_oimt_pic)
  165. # ------------------------------------------------------------------
  166. if len(all_type) == len(con11):
  167. if not is_from_0:
  168. if all_type[num] and all_type[num].replace("题", "") not in ['选择', '单选', '多选', '不定选择']:
  169. one_item_split = one_item_split[1:]
  170. else: # 针对选择题第1题或前面几题题号漏了的情况
  171. one_item_split1 = one_item_split[1:]
  172. # ------针对分错的细节继续拆分,如上一题选项行与下一题题干没有换行-----------------
  173. new_one_item_split = []
  174. pattern_1 = re.compile(
  175. r"([CDE]\s*[..、、].+?)(?<![::])\s([1-9]|1[0-9])\s*[..、、](.+?([是为有]|等于)[((]\s*[))]\n)")
  176. pattern_2 = re.compile(
  177. r"(([CDE]\s*[..、、]|\([CDE]\)).+?)(?<![::])\s\(([1-9]|1[0-9])\)(.+?([是为有]|等于)[((]\s*[))]\n)")
  178. for nn, one_item in enumerate(one_item_split1):
  179. if item_no_type == 1 and re.search(pattern_1, one_item):
  180. err_optcon = re.sub(pattern_1, r"\1【】\3", one_item) # 太粗糙了
  181. new_one_item_split.extend(err_optcon.split("【】"))
  182. items_no_temp.insert(nn+1, int(re.search(pattern_1, one_item).group(2)))
  183. elif item_no_type == 2 and re.search(pattern_2, one_item):
  184. err_optcon = re.sub(pattern_2, r"\1【】\4", one_item)
  185. new_one_item_split.extend(err_optcon.split("【】"))
  186. items_no_temp.insert(nn + 1, int(re.search(pattern_2, one_item).group(3)))
  187. else:
  188. new_one_item_split.append(one_item)
  189. if re.match(r'(^|\n)+\s*[A-Z]\s*[..、、]|(^|\n)+\s*[((]\s*[A-Z]\s*[))]\s*[..、、]?',
  190. str(one_item_split[0]).strip(), re.S) or \
  191. re.search("如[上下左右]图|[((]\s+[))]\s*($|\n)", one_item_split[0].strip()):
  192. new_one_item_split.insert(0, one_item_split[0])
  193. items_no_temp.insert(0, items_no_temp[0]-1)
  194. one_item_split = new_one_item_split
  195. # ----------------------------------------------------------
  196. if all_type[num] in item_type_classify: # 统计每类题型含有的题目个数
  197. item_type_classify[all_type[num]] += len(one_item_split)
  198. elif all_type[num]:
  199. item_type_classify[all_type[num]] = len(one_item_split)
  200. item_type_num.append((all_type[num], len(one_item_split)))
  201. else:
  202. if not is_from_0:
  203. one_item_split = one_item_split[1:]
  204. new_item_no.extend(items_no_temp)
  205. # ---------------------------------------------------------------
  206. # 从题型行中判断单选和多选 放在这里收集也可以:可可能出现两不同题型行提到的序号一样
  207. # choice_class = {}
  208. # if all_type[num] == "选择题":
  209. # multi_choice_info = re.findall("[\s,,;;((]+第?(\d+)[至到\-~]+(\d+)题[是为]([多单])项?选择?题?",
  210. # all_type_info[num][2])
  211. # if multi_choice_info:
  212. # for mu in multi_choice_info:
  213. # choice_class[mu[2]] = list(range(int(mu[0]), int(mu[1]) + 1))
  214. # ---------------------------------------------------------------
  215. dd = {}
  216. for nn, one_item in enumerate(one_item_split):
  217. # 针对多个题共用一段材料的情况2021-11-3
  218. if subject == "地理":
  219. res, com_stem, item_groups = split_with_comstem(head_item, one_item_split, res, nn, item_groups)
  220. if com_stem:
  221. dd.update(com_stem)
  222. # common_stem_may = re.search("(完成|回答)下?[面列]?的?第?(\d{1,2})[-到至第~~-]+?(\d{1,2})题",
  223. # one_item.replace(" ", "").replace("\n", ""))
  224. # if subject == "地理" and common_stem_may:
  225. # common_stem_info = re.search("((\n\s*[ABCDE][^\n]+?\n?)+)\n", one_item, flags=re.S)
  226. # if common_stem_info:
  227. # common_stem = one_item[common_stem_info.end():]
  228. # item_groups["pos"].append(up_num+nn+2)
  229. # item_groups["{}-{}".format(common_stem_may.group(2),
  230. # common_stem_may.group(3))] = common_stem
  231. # one_item = one_item[:common_stem_info.end()]
  232. # item_groups["{}-{}".format(common_stem_may.group(1), common_stem_may.group(2))] = head_item
  233. dd["stem"] = one_item
  234. #------------------对每个大题的第一题加上may_oimt_pic--------------------------
  235. if nn==0 and may_oimt_pic:
  236. dd['susp_pic'] = may_oimt_pic
  237. # ------------------------------------------------------------------------
  238. dd["item_id"] = items_no_temp[nn]
  239. dd["score"] = each_item_score[num]
  240. if not dd["score"] and each_item_score2 and str(dd["item_id"]) in each_item_score2.keys():
  241. dd["score"] = each_item_score2[str(dd["item_id"])]
  242. dd["errmsgs"] = []
  243. if all_type[num] and re.search("必考基础综合中等面列下各非", all_type[num]) is None:
  244. dd["type"] = all_type[num] if re.sub('[((]', "", all_type[num]) != '本大题' else "解答题"
  245. else:
  246. dd["type"] = ""
  247. if choice_class:
  248. for k, v in choice_class.items():
  249. if dd["item_id"] in v:
  250. dd["type"] = k + "选题"
  251. # elif len(choice_class) == 1:
  252. # dd["type"] = "多选题" if k == "单" else "单选题"
  253. if select_type_id and dd["item_id"] in select_type_id:
  254. dd['is_optional'] = 'true'
  255. if len(one_item_split) == 1 and dd["score"] == 0.0 and title_info_dict["total_score"][num] > 0.0:
  256. dd["score"] = title_info_dict["total_score"][num]
  257. res.append(dd)
  258. # 多图在一起的情况进行拆分
  259. # if len(re.findall(r"第?\(?([1-9]|[1-4][0-9])\)?\s*题图", one_item)) > 1 and \
  260. # re.search(r"<imgsrc\d.+?\n+\s*第?\(?([1-9]|[1-4][0-9])\)?\s*题图", one_item, re.S):
  261. pic_info = re.search(r"(<imgsrc\d.+?)\n+\s*((第?\(?([1-9]|[1-4][0-9])\)?\s*题图.?\s*){2,})", one_item, re.S)
  262. if pic_info:
  263. pic_list = re.findall(r"<imgsrc\d.*?/>", pic_info.group(1))
  264. pic_w = re.findall("([1-9]|[1-4][0-9])[))]?\s*(?=题)", pic_info.group(2))
  265. if len(pic_list) >= len(pic_w):
  266. pic_no = {int(p): pic_list[len(pic_list) - len(pic_w) + k] for k, p in enumerate(pic_w)}
  267. dd["stem"] = dd["stem"].replace(pic_info.group(2), "")
  268. for k, pic in enumerate(pic_list[::-1]):
  269. if k < len(pic_w):
  270. dd["stem"] = dd["stem"].replace(pic, "")
  271. # -----------------------------------------------------
  272. dd = {}
  273. if pic_no:
  274. for i in list(pic_no.keys()):
  275. res[i-1]["stem"] = res[i-1]["stem"].strip() + "\n" + pic_no[i] + "\n" + "第" + str(i) + "题图"
  276. # ----------------------------------------------------------------------
  277. # 可能出现选择题类的选做题
  278. # --------最后判断一下题量是否正确-----------------------------------------
  279. # 针对拆分后题量特别多的情况,将拆分后题量与已知题量一样的题目保留
  280. new_res = []
  281. right_type = [] # 记录与已知题目个数一样的分块{第几个分块,题型}
  282. if all_type and sum(list(item_type_classify.values())) > 40: # 很可能存在大片不是题号的题号
  283. title_type_num_all = sum([t[1] for t in title_type_num]) # 题型行给出的题目个数
  284. if title_type_num_all > 0:
  285. for idx, type_num in enumerate(item_type_num):
  286. if type_num[1] == title_type_num[idx][1] > 0: # 同一题型是否题量一致
  287. right_type.append((idx, type_num[0]))
  288. elif title_type_num[idx][1] == 0 and type_num[1] == 1:
  289. title_type_num[idx][1] = 1
  290. right_type.append((idx, type_num[0]))
  291. if right_type:
  292. for rtype in right_type:
  293. for idx, item in enumerate(res):
  294. r_st = 0 if rtype[0]==0 else sum([t[1] for t in item_type_num[:rtype[0]]])
  295. r_ed = r_st + item_type_num[rtype[0]][1]
  296. if item["type"] == rtype[1] and r_st<=idx<r_ed:
  297. new_res.append(item)
  298. res = new_res
  299. item_type_num = title_type_num # 将题目已知题型数量信息作为正确信息
  300. new_item_type_classify = {}
  301. for i in right_type:
  302. if title_type_num[i[0]][0] not in new_item_type_classify:
  303. new_item_type_classify[title_type_num[i[0]][0]] = title_type_num[i[0]][1]
  304. else:
  305. new_item_type_classify[title_type_num[i[0]][0]] += title_type_num[i[0]][1]
  306. item_type_classify = new_item_type_classify
  307. return res, all_type, item_type_classify, item_no_type, item_type_num, new_item_no, item_groups
  308. def split_with_comstem(head_cons, one_item_split, bef_res, pc_idx, item_groups):
  309. """
  310. head_cons: 每类题最前面的题文部分
  311. one_item_split:按题号切分的试题list
  312. bef_res:前面已经初步结构化好的题目
  313. pc_idx: 索引计时器
  314. :return:
  315. """
  316. if not pc_idx: # 没有题型行,第一题前
  317. mix_con = "\n".join(head_cons).strip()
  318. else:
  319. mix_con = one_item_split[pc_idx - 1].strip()
  320. common_stem_info1 = re.search("(完成|回答)下?[面列]?的?第?(\d{1,2})[-到至第~~-]+?(\d{1,2})题",
  321. mix_con.replace(" ", "").replace("\n", ""))
  322. common_stem_info2 = re.search("(完成|回答)下?[面列]?的?.*?[\d小]题.{,2}\n?(<imgsrc.*?/>[\s\n]*?)*?.{,2}$", mix_con, flags=re.S)
  323. bef_con = ""
  324. one_res = {}
  325. if common_stem_info2:
  326. item_groups["is_groups"] = 1
  327. if common_stem_info1:
  328. st = common_stem_info1.group(2)
  329. end = common_stem_info1.group(3)
  330. if not item_groups["groups_data"]:
  331. item_groups["groups_data"][0] = "{}-{}".format(st, end)
  332. else:
  333. item_groups["groups_data"][len(bef_res)] = "{}-{}".format(st, end)
  334. else:
  335. item_groups["groups_data"][len(bef_res)] = ""
  336. com_stem = ""
  337. if re.search("【题文】", mix_con):
  338. bef_con, com_stem = mix_con.split("【题文】", maxsplit=1)
  339. else:
  340. com_stem_idx = [i.end() for i in re.finditer(r"(所以|故而?).{,3}(选择?[A-Fa-f]选?项?"
  341. r"|选项[A-Fa-f]正确).{,2}\n"
  342. r"|(\n\s*[A-E]\s*[..、、::][^\n]*?\n?)+\n", mix_con,flags=re.S)]
  343. if com_stem_idx:
  344. com_stem = mix_con[com_stem_idx[-1]:]
  345. bef_con = mix_con[:com_stem_idx[-1]]
  346. else:
  347. if not pc_idx:
  348. com_stem = mix_con
  349. else:
  350. mix_con_list = mix_con.split(r"(详解】|解析】|答案】)")
  351. if len(mix_con_list) > 2: # 含解析
  352. bef_con = "".join(mix_con_list[:-1])
  353. mix_con = mix_con_list[-1]
  354. else:
  355. mix_con = mix_con_list[0]
  356. paras = mix_con.split("\n") # 将混淆的部分换行拆分
  357. paras = [para for para in paras if para.strip()] # 去掉空行
  358. if len(paras) > 1:
  359. if len(paras) == 2 or len(paras[-1]) >= 20: # 2段or段长
  360. com_stem = paras[-1]
  361. bef_con = bef_con + "\n".join(paras[:-1])
  362. else:
  363. com_stem = paras[-2:]
  364. bef_con = bef_con + "\n".join(paras[:-2])
  365. else:
  366. bef_con = bef_con + "\n".join(paras)
  367. # 此时 com_stem 为空
  368. if com_stem and bef_res:
  369. bef_res[-1]["stem"] = bef_con
  370. one_res["com_stem"] = com_stem
  371. return bef_res, one_res, item_groups