option.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  1. #!/usr/bin/env/python
  2. # -*- coding:utf-8 -*-
  3. import re
  4. from utils.washutil import table_label_cleal
  5. import numpy as np
  6. def option2block(option_con, item_no_type):
  7. """
  8. 选择题选项切分
  9. 对于选项切分部分,最好也像题号一样先自我切分纠错,但这样老师如果手误打错了字母,可能就解析出错!!!!!
  10. :return:
  11. """
  12. def del_table(ss):
  13. ss = re.sub(r"</?t[dr]>|</?tbody>|</?table>|</?div>|</?p>", "", ss.replace("<td><p>", " "))
  14. return ss
  15. # print('***********',option_con)
  16. if '<table><tbody><tr>' in option_con and \
  17. len(re.findall('<tr><td><p>(A\s*[..、、].+?|\(A\)\s*[..、、]?.+?)</tr>', option_con.strip())) == 1:
  18. st_opt = re.search('<table><tbody><tr><td><p>(A\s*[..、、].+?|\(A\)\s*[..、、]?.+?)</tr>', option_con.strip()).start()
  19. option_con = option_con.strip()[0:st_opt] + '\n' + del_table(option_con.strip()[st_opt:])
  20. # print("option_con:", option_con)
  21. option_con = re.sub(r"</table>\n*?\s*<p>\s*(A\s*[、、..]|\(A\)\s*[、、..]?)(.+?)", r"\n【【\1】】\2", option_con, re.S)
  22. if re.search("\n\s*C", option_con) is None and re.search("\n\s*c", option_con):
  23. option_con = re.sub("\n\s*c", "\nC", option_con)
  24. option_con = re.sub(r"(\n\s*(<img\s*src=.+?>\s*)+?\s*)(A[、、..].+?)", r"\1\n\3", option_con.strip())
  25. con = re.sub(r"\n\s*([A-H])\s*[、、..](.+?)", r"\n【【\1、】】\2", option_con.strip()) # 行首的A、不能考虑,故得用strip
  26. if item_no_type == 1 and len(re.findall(r'【【[A-H]\s*[..、、]】】', con)) <= 2 and \
  27. len(re.findall(r'\([A-H]\)', con)) > 2: # 针对题干是第一种类型,选项是第二种类型的情况
  28. item_no_type = 2
  29. if item_no_type == 2:
  30. con = re.sub(r"\n\s*\(([A-Hc])\)\s*[、、..]?(.+?)", r"\n【【\1、】】\2", option_con)
  31. if item_no_type == 1:
  32. if len(re.findall(r'【【[A-H]\s*[..、、]】】', con)) <= 3:
  33. while re.search(r"\n\s*[A-H]\s*<img\s*src=.+?", con.replace(" ", "")): # 2020/7/15
  34. con = re.sub(r"\n\s*([A-H])\s*(<img\s*src=.+?)", "\n" + r"【【\1、】】\2", con)
  35. while re.search(r"(\n\s*<img\s*src=.+?)([A-H][..、、])(.+?)", con.replace(" ", "")):
  36. con = re.sub(r"(\n\s*<img\s*src=.+?)(?<!【)([A-H]\s*[..、、])(.+?)", r"\1" + "\n" + r"【【\2】】\3", con)
  37. while re.search(r"(\n【【[A-H][..、、]】】.+?)(?<!【)([A-Hc][..、、])\n+(.+?)(?<!【)([A-H][..、、])(.+?)",
  38. con.replace(" ", ""), re.S):
  39. con = re.sub(r"(\n\s*【【[A-H]\s*[..、、]】】.+?)(?<!【)([A-H]\s*[..、、])\s*\n+(.+?)"
  40. r"(?<!【)([A-H]\s*[..、、])(.+?)", r"\1【【\2】】\3【【\4】】\5", con, flags=re.S)
  41. while re.search(r"(\n【【[A-H][..、、]】】.+?)(?<!【)([A-H][..、、])\n+(.+?)", con.replace(" ", ""), re.S):
  42. con = re.sub(r"(\n\s*【【[A-H]\s*[..、、]】】.+?)(?<!【)([A-H]\s*[..、、])\s*\n+(.+?)",
  43. r"\1【【\2】】\3", con, flags=re.S)
  44. while re.search(r"(\n【【[A-H][..、、]】】.+?)(?<!【)([A-H][..、、])(.+?)", con.replace(" ", "")):
  45. con = re.sub(r"(\n\s*【【[A-H]\s*[..、、]】】.+?)(?<!【)([A-H]\s*[..、、])(.+?)", r"\1【【\2】】\3", con)
  46. while re.search(r"(\n【【[A-H][..、、]】】[^【]+?/>\s+)(?<!【)([B-H][..、、])(.+?)", con.replace(" ", ""), re.S):
  47. con = re.sub(r"(\n\s*【【[A-H]\s*[..、、]】】[^【]+?/>\s+)(?<!【)([B-H]\s*[..、、])\s*(.+?)",
  48. r"\1【【\2】】\3", con, flags=re.S) # 选项子母前面是图片 9/8
  49. if item_no_type == 2:
  50. if len(re.findall(r'【【[A-H][..、、]】】', con)) <= 3:
  51. while re.search(r"\n\s*\([A-H]\)\s*<imgsrc=.+?", con.replace(" ", "")): # 2020/7/15
  52. con = re.sub(r"\n\s*\(([A-H])\)\s*(<img src=.+?)", "\n" + r"【【\1、】】\2", con)
  53. while re.search(r"(\n\s*<imgsrc=.+?)(\([A-H]\)[..、、]?)(.+?)", con.replace(" ", "")):
  54. con = re.sub(r"(\n\s*<img src=.+?)\(([A-H])\)\s*[..、、]?(.+?)", r"\1" + "\n" + r"【【\2、】】\3", con)
  55. while re.search(r"(\n【【[A-H]、】】.+?)\(([A-H])\)[..、、]?\n+(.+?)\(([A-H])\)[..、、]?(.+?)",
  56. con.replace(" ", ""), re.S):
  57. con = re.sub(r"(\n\s*【【[A-H]、】】.+?)\(([A-H])\)\s*[..、、]?\s*\n+(.+?)"
  58. r"\(([A-H])\)\s*[..、、]?(.+?)", r"\1【【\2、】】\3【【\4、】】\5", con, flags=re.S)
  59. while re.search(r"(\n【【[A-H]、】】.+?)\(([A-H])\)[..、、]?\n+(.+?)", con.replace(" ", ""),re.S):
  60. con = re.sub(r"(\n\s*【【[A-H]、】】.+?)\(([A-H])\)\s*[..、、]?\s*\n+(.+?)",
  61. r"\1【【\2、】】\3", con, flags=re.S)
  62. while re.search(r"(\n【【[A-H]、】】.+?)\(([A-H])\)[..、、]?(.+?)", con.replace(" ", "")):
  63. con = re.sub(r"(\n\s*【【[A-H]、】】.+?)\(([A-H])\)\s*[..、、]?(.+?)", r"\1【【\2、】】\3", con)
  64. con_list = re.split(r"【【[A-H]\s*[..、、]】】", con)
  65. if len(con_list) > 1:
  66. stem_opt = table_label_cleal(con_list[0])
  67. con_list = list(map(del_table, con_list[1:]))
  68. con_list.insert(0, stem_opt) # 题干中的表格不需要清洗
  69. return con_list, con
  70. recur_n = 1 # 递归次数
  71. def option_structure(one_item, con, ans, item_no_type):
  72. """
  73. 选择题选项拆分结构化
  74. 还需要判断一下 选项个数与题型的对应!!!!
  75. :return:
  76. """
  77. global recur_n
  78. # print(con)
  79. # print('----------------------')
  80. if recur_n>2:
  81. if 'options' not in one_item:
  82. one_item["errmsgs"].append("选项格式不正确")
  83. recur_n = 1
  84. return one_item
  85. ans = re.sub("[;;.]+", "", ans)
  86. ans2 = []
  87. for a in ans.split("#"):
  88. if 0<len(a.replace(" ", "")) < 8:
  89. ans2.append("、".join(re.findall(r"[A-G]", a)))
  90. one_item["answer"] = "; ".join(ans2)
  91. # options_rank = get_options_arrange(one_item["content"])
  92. # print("id:", one_item['item_id'])
  93. # print("options_rank:",options_rank)
  94. con_list, repl_con = option2block(con, item_no_type)
  95. # print(len(con_list), con_list)
  96. # print('----------------------------')
  97. # 初筛
  98. if len(con_list) < 5:
  99. opt_letter = re.findall(r"【【([A-H])\s*[..、、]】】", repl_con)
  100. if opt_letter and opt_letter[0] == 'B' and re.search("<img src=.+?/>\s*A\s*[..、、].+?$", con_list[0]):
  101. re_split = re.sub("(<img src=.+?/>)\s*A\s*[..、、](.+?)$", r"\1【【A、】】\2", con_list[0])
  102. con_list[0] = re_split.split("【【A、】】")[0]
  103. con_list.insert(1, re_split.split("【【A、】】")[1])
  104. if len(con_list) >= 5:
  105. pattern_1 = re.compile(r"\s([1-9]|1[0-9])[..、、].+?([是为有]|等于)[((]\s*[))]\n", re.S)
  106. pattern_2 = re.compile(r"\s\(([1-9]|1[0-9])\).+?([是为有]|等于)[((]\s*[))]\n", re.S)
  107. pattern_3 = re.compile(r"([是为有]|等于)[((]\s*[))]\n", re.S)
  108. # 第一个错误针对题目中没有答案解析的情况,不然就是选项切分错误
  109. if (item_no_type == 1 and any([True for op in con_list[1:] if re.search(pattern_1, op)])) or \
  110. (item_no_type == 2 and any([True for op in con_list[1:] if re.search(pattern_2, op)])):
  111. one_item["errmsgs"].append("本题选项与下一题题干间没有换行符,请注意重新换行!!!") # 一般只有一题和上一题连在一起
  112. one_item['spliterr_point'] = one_item['item_id']
  113. return one_item
  114. elif any([True for op in con_list[1:] if re.search(pattern_3, op)]):
  115. one_item["errmsgs"].append("本题的下一题的题号有问题,请注意重新输入!!!")
  116. one_item['spliterr_point'] = one_item['item_id']
  117. # ------------------------------------------------------------------------
  118. aft_opt = [] # 针对选项后是题目图片的情况
  119. if "\n" in con_list[-1]:
  120. ccon = re.split("\n+", con_list[-1])
  121. while re.match("<img src=", ccon[-1]) and len(ccon) > 1:
  122. aft_opt.insert(0, ccon[-1])
  123. ccon = ccon[:-1]
  124. if aft_opt:
  125. con_list[0] += "\n" + "\n".join(aft_opt)
  126. con_list[-1] = "\n".join(ccon)
  127. # -------------------------------------------------------------------------
  128. # 选项纠错
  129. con_list[0] = re.sub(r"\(\d+分\)", "", con_list[0][:9]) + con_list[0][9:]
  130. opt_letter = re.findall(r"【【([A-H])\s*[..、、]】】", repl_con)
  131. # print('/////////////////////////',opt_letter)
  132. if "".join(sorted(opt_letter)) in "ABCDEFGHIJ" or "".join(sorted(opt_letter)) in ["ABCE", "ABDE", "ACDE", "BCDE"]:
  133. # con_list = pic_transfer(con_list)
  134. if con_list:
  135. return dict(one_item, **{"content": con_list[0],
  136. "options": [re.sub("(<br/>|\n)\s*$|\s+$", "", i) for i in con_list[1:]],
  137. }) # "options_rank": options_rank, "options_num": len(con_list[1:])
  138. else:
  139. # 初次选项拆分的错误判断
  140. con_list = option_label_correct(opt_letter, con_list, repl_con)
  141. # double_l = [key for key, value in dict(Counter(opt_letter)).items() if value > 1]
  142. if type(con_list) == str:
  143. one_item["errmsgs"].append(con_list)
  144. return one_item
  145. else:
  146. # con_list = pic_transfer(con_list)
  147. if con_list:
  148. return dict(one_item,
  149. **{"content": con_list[0],
  150. "options": [re.sub("(<br/>|\n)\s*$|\s+$", "", i) for i in con_list[1:]],
  151. })
  152. # return dict(one_item, **dict(zip(["content","A","B","C","D"], con_list)))
  153. else:
  154. # 选项可能放在表格中
  155. is_fail = 0
  156. con_list2 = re.split(r"\n+", con)
  157. errmsgs = ""
  158. if len(con_list2) == 2: # 选项是4个图片组成的情况
  159. option_array = len(re.findall("(^|\n)<img src=.+?", con_list2[1].strip()))
  160. if option_array > 2: # 排列情况
  161. options_rank = 1
  162. elif option_array > 1:
  163. options_rank = 3
  164. else:
  165. options_rank = 2
  166. con_list2 = [con_list2[0] if k == 0 else "<img src=" + v
  167. for k, v in enumerate(con_list2[1].split("<img src="))]
  168. if len(con_list2) == 5:
  169. con_list2[0] = re.sub(r"\(\d+分\)", "", con_list2[0].replace(" ", "")[:9]) + con_list2[0][9:]
  170. return dict(one_item, **{"content": con_list2[0],
  171. "options": [re.sub("(<br/>|\n)\s*$|\s+$", "", i) for i in con_list2[1:]],
  172. })
  173. else:
  174. errmsgs = """选项格式不正确,请改为: A.xxxx B.xxx 或 (A)xxxx (B)xxx,全文选项和题号格式要统一。
  175. 【注意】1>>选项和题干间要换行,选项不要放在表格中;2>>选项【如A.】重新手输;3>>选项图片时用嵌入式;
  176. 4>>选项太长时,每项之间要换行,上一项的内容不要与下一项在同一行!!"""
  177. is_fail = 1
  178. else:
  179. con_list3 = re.split(r"\n<img", con)
  180. if len(con_list3) == 5:
  181. return dict(one_item, **{"content": con_list3[0],
  182. "options": [re.sub("(<br/>|\n)\s*$|\s+$", "", i) for i in con_list3[1:]],
  183. })
  184. else:
  185. errmsgs = """选项格式不正确,请改为: A.xxxx B.xxx 或 (A)xxxx (B)xxx,全文选项和题号格式要统一。
  186. 【注意】1>>选项和题干间要换行,选项不要放在表格中;2>>选项【如A.】重新手输;3>>选项图片时用嵌入式;
  187. 4>>选项太长时,每项之间要换行,上一项的内容不要与下一项在同一行!!"""
  188. is_fail = 1
  189. op_con = re.split("[((]\s*[))]", con)[-1]
  190. stem_con = "".join(re.split("[((]\s*[))]", con)[:-1])+"( )\n"
  191. if is_fail:
  192. if "table" in op_con:
  193. to_clean_con = re.findall('<table>(((?!(</?table>)).)*)</table>', op_con, re.S)
  194. if len(to_clean_con) == 1:
  195. op_con = re.sub("</?table>|</?tr>|</?td>", "", op_con)
  196. one_item = option_structure(one_item, stem_con+op_con, ans, item_no_type)
  197. else:
  198. aa = re.findall("[A-E]", op_con)
  199. if len(aa)==len(set(aa)) == 4:
  200. recur_n += 1
  201. op_con = re.sub("([A-E])\s*(?![..、、])", r"\1、", op_con)
  202. one_item = option_structure(one_item, stem_con + op_con, ans, item_no_type)
  203. if 'options' not in one_item and "选项格式不正确" not in "".join(one_item["errmsgs"]):
  204. one_item["errmsgs"].append(errmsgs)
  205. return one_item
  206. def get_options_arrange(cont):
  207. """
  208. 判断word中选项每行排版个数
  209. :return:
  210. """
  211. options_rank = 1 # 纵向排列
  212. option_num = 0
  213. if '<table><tbody><tr>' in cont:
  214. table_op = re.findall('<tr>.+?>([A-H]\s*[..、、].+?|\([A-Z]\)\s*[..、、]?.+?)</tr>', cont.strip())
  215. if table_op:
  216. option_num = len(re.findall('[A-H]\s*[..、、].+?|\([A-Z]\)\s*[..、、]?.+?', table_op[0]))
  217. if option_num == 2:
  218. options_rank = 3
  219. if option_num > 2:
  220. options_rank = 2
  221. else:
  222. option_list = cont.split("\n")
  223. for op in option_list:
  224. if re.search("^\s*[A-H]\s*[..、、].+?|^\s*[A-H]\s*<img src=.+?|^\s*\([A-Z]\)\s*[..、、]?.+?", op.strip()):
  225. option_num += 1
  226. if option_num == 2:
  227. options_rank = 3 # 一排2个
  228. elif option_num < 2:
  229. options_rank = 2 # 横向排列
  230. return options_rank
  231. def option_label_correct(opt_letter, con_list, con):
  232. """
  233. 选项少切了会报错,所以优先解决多切的错误问题
  234. 纠正中标签错误的情况:选项字母不连续或重复;
  235. opt_letter:选项的字母 con_list:选择题拆分了选项的列表
  236. """
  237. lable_sign = re.findall(r"【【([A-H][..、、])】】", con.replace(" ", ""))
  238. con_list2 = con_list
  239. for i, j in enumerate(lable_sign): # 将con_list的选项字母加上
  240. con_list[i + 1] = j + con_list[i + 1]
  241. # con_list2 = re.split(r"【【[A-H]\s*[..、、]】】", con)
  242. p1 = 0 # 选项在con_list中的起始位置
  243. for k, v in enumerate(con_list[1:]):
  244. if re.search(r"[((]\s*[))]", v): # 选择题末尾一般都有()
  245. opt_letter[k] = '0'
  246. p1 = k + 2
  247. if p1 and p1 < len(con_list[1:]): # '0'不在最后一个位置
  248. option_list = con_list2[p1:]
  249. if len(option_list) >= 4:
  250. new_con_list = ["".join(con_list[:p1])].extend(option_list)
  251. return new_con_list
  252. else: # 只考虑ABCD和ACBD两种情况
  253. label_str = "".join(opt_letter)
  254. if re.match("A","".join(opt_letter)) is None:
  255. label_str = re.sub("[^A]A", "0A", "".join(opt_letter), count=1)
  256. # print(label_str)
  257. # -------------------------------------------------------------
  258. # 若选择题中没有(),题干中还是出现了AA的话,需要判断下是否存在错误
  259. if re.search("AA", label_str):
  260. label_bcd_idx = [k for k, i in enumerate(label_str) if i != 'A']
  261. label_a_idx = [k for k, i in enumerate(label_str) if i == 'A']
  262. length_all = []
  263. for i1 in label_bcd_idx: # 先将公式替换,作选项长度判断
  264. l1 = len(re.sub(r"<img\s*src\s*=\s*((?!/>).)+?/>", "<img>", con_list2[i1+1]).replace(" ",""))
  265. length_all.append(l1)
  266. aver_length = np.mean(length_all)
  267. st_a = label_str.index("AA")
  268. for i2 in label_a_idx:
  269. l2 = len(re.sub(r"<img\s*src\s*=\s*((?!/>).)+?/>", "<img>", con_list2[i2+1]).replace(" ",""))
  270. if abs(l2 - aver_length) >= 12:
  271. if i2 >= st_a:
  272. st_a = i2+1
  273. if st_a < len(label_str)-3:
  274. label_str = "".join(["0" if k < st_a else i for k, i in enumerate(label_str)])
  275. # -----------------------------------------------------------------
  276. label_str = re.sub("A[^BC]", "AA", label_str)
  277. label_str = re.sub("B[^CD]", "BB", label_str)
  278. label_str = re.sub("C[^BD]", "CC", label_str)
  279. label_str = re.sub("D[^E]", "DD", label_str)
  280. # 统计是否有重复的字符,若有,则进行合并,否则保持原来
  281. new_con_list = [con_list[0]]
  282. local_w = 0
  283. while local_w < len(label_str):
  284. while label_str[local_w] == '0': # 如果‘0’在中间,则‘0’会被去除
  285. local_w += 1
  286. double_num = label_str.count(label_str[local_w])
  287. if double_num >= 2:
  288. new_con_list.append(con_list2[local_w + 1] + "".join(con_list[2 + local_w:local_w+double_num + 1]))
  289. else:
  290. new_con_list.append(con_list2[local_w + 1])
  291. local_w += double_num
  292. new_opt_letter = label_str.replace('AA',"A").replace('BB',"B").replace('CC',"C").replace('DD',"D")
  293. if len(new_con_list) >= 4:
  294. if "".join(sorted(new_opt_letter)) in "ABCDEFGHIJ" or "".join(sorted(new_opt_letter)) in ["ABCE", "ABDE", "ACDE", "BCDE"]:
  295. return new_con_list
  296. return "选项格式不正确,1、请改为: A.xxxx B.xxx,手动输入选项字母及后面的标点符号;" \
  297. "2.第一个选项A与题干之间要换行,各选项按ABCD排序;3.选项含图片时用嵌入式;"