123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992 |
- #!/usr/bin/env/python
- # -*- coding:utf-8 -*-
- import re
- from utils.washutil import table_label_cleal, del_no
- from utils.topic_no import *
- def anss_structure_with_type(item_res, ans_str, all_type, all_type2,item_type_num,item_type_classify):
- """
- 针对含题型行的答案进行结构化
- :return:
- """
- rd1_is_fail = 0
- is_amount_wrong = 0
- if len(all_type2) == len(all_type):
- # try:
- if not all_type[0]: # 第一大题型不存在
- all_type[0] = all_type2[0]
- if all_type.count(all_type[0]) > 1:
- item_type_classify[all_type[0]] += item_type_num[0][1]
- if sorted(all_type) != sorted(all_type2): # !!!!!!还需细分
- print("题文和答案中的题型不一致,题文中的题型={},答案中的题型={}".format(str(all_type), str(all_type2)))
- ans22 = re.split(r"\n\s*[一二三四五六七八九十]\s*[、..、::]\s*[^必考基础综合中等]{2,4}题.*?[分。.]?\s*(?=\n)"
- r"|\n\s*[、..、::]?\s*[单多]选题.*?[分。.]?\s*(?=\n)"
- r"|\n\s*[、..、::]?\s*[不定非]*?选择题.*?[分。.]?\s*(?=\n)"
- r"|\n\s*[、..、::]?\s*填空题.*?[分。.]?\s*(?=\n)"
- r"|\n\s*[、..、::]?\s*[解简答作图论述探究计算]+?题.*?[分。.]?\s*(?=\n)", ans_str)
- while re.search(r"[A-H\u4e00-\u9fa5]", ans22[0]) is None:
- del ans22[0]
- ans22 = [i for i in ans22 if i.strip()]
- if len(ans22) > len(all_type):
- rd1_is_fail = 1
- return item_res, rd1_is_fail
- ans_item_no_type = judge_ans_no_type(ans22, item_type_num) # 初步判断答案中的题号类型
- # print("tihao类型:", ans_item_no_type)
- # -----------------------------------------------------------------
- # 开始按题号切分题目!!!!!!!!!!!!!!!
- type_id = 0
- new_ans_no = []
- all_ans = []
- for num, one_type in enumerate(ans22):
- # 当前题型中的题目数量(以试题的题目个数为准)
- # one_type_num = item_type_classify[all_type[num]]
- # if len(all_type2) != len(item_type_classify): # 存在重复题型
- one_type_num = item_type_num[num][1]
- print("one_type_num :", one_type_num)
- # 1>> 先按题号都在行首的情况(一行不多于一个答案)
- item_id = 0
- one_type_ans = []
- one_type_no = []
- # 规范化
- one_type = re.sub("\n\s*(\${*?)([1-9][0-9]|[1-9])\s*([..、、])(.+?)", r"\n\2\3\1\4", one_type)
- one_type = re.sub("\$(([1-9][0-9]|[1-9])\s*[..、、].+?)", r"$ \1", one_type)
- one_type = re.sub("(\${*?)([1-9][0-9]|[1-9])\s*([..、、])\s*(?!\d)", r" \2\3\1", one_type)
- item_no_info = pre_get_item_no('\n'+one_type, ans_item_no_type) # 初步按非表格非排列的形式获取题号信息
- print("初步题号11:", item_no_info)
- if not item_no_info:
- # 表格答案和排列型答案应该不同时存在!!!
- if "table" in one_type:
- if "选" not in all_type2[num] and "选" not in all_type[num]: # 不是选择题则去掉表格格式
- one_type = get_table_ans(one_type, new_ans_no, flag=2) # 去掉表格中的换行符,无用
- item_no_info = pre_get_item_no('\n' + one_type, ans_item_no_type)
- else:
- # 存在表格答案
- ans_no, table_ans = get_table_ans(one_type, new_ans_no)
- print("表格答案11:",table_ans, ans_no)
- if table_ans:
- one_type_ans.extend(table_ans)
- one_type_no.extend(ans_no)
- else:
- one_type_no, one_type_ans = get_array_ans(one_type, new_ans_no, item_res[0]['item_id'],
- temp_type=all_type[num])
- if item_no_info: # 一行多个时,可能初步提取的题号只有1-2个
- # 表格答案和1-10BCCDBB 答案类型 应该不同时存在吧
- local_ans_no1, items_no_idx = get_right_no(item_no_info)
- print("local_items_no:", local_ans_no1)
- print("local_items_no_idx:", items_no_idx)
- is_from_0 = 1 # shi
- if items_no_idx[0] != 0 and local_ans_no1[0] > 1:
- items_no_idx.insert(0, 0)
- is_from_0 = 0 # fei
- one_item_split = [("\n" + one_type)[i:j] for i, j in zip(items_no_idx, items_no_idx[1:] + [None])]
- while re.search("<table>.*?</table>", one_item_split[0], flags=re.S):
- ans_no, table_ans = get_table_ans(one_item_split[0],new_ans_no)
- one_type_ans.extend(table_ans)
- one_type_no.extend(ans_no)
- one_item_split[0] = re.sub("<table>(((?!(</?table>)).)*)</table>", "", one_item_split[0], flags=re.S)
- if not is_from_0:
- if re.match('(\n|^)故[::]?选[::]|故[::]?答案分?别?[为是]?'
- '|【([解分][析答]|详解|点[评睛])】|(答案|解析|详解)[::]',
- one_item_split[0].replace(" ", "")) is None:
- raw_items_no = [int(i[1]) for i in item_no_info]
- # print("2021-10-20:", new_ans_no[-1], raw_items_no[0])
- if new_ans_no and new_ans_no[-1] != raw_items_no[0] - 1:
- one_item_split = one_item_split[1:]
- items_no_idx = items_no_idx[1:]
- else:
- local_ans_no1.insert(0, local_ans_no1[0]-1)
- # -------开始判断答案个数是否正确------------------------
- one_type_no1 = one_type_no.copy()
- one_type_no1.extend(local_ans_no1)
- print('开始:', one_type_no1, one_type_num)
- if len(one_type_no1) != one_type_num:
- # 存在一行多个的情况,题号前必须有空格
- one_type_str = '\n' + '\n'.join(one_item_split) # 本部分的str,要保留题号信息
- ans_no1, ans_no_idx1 = get_many_ans_no(one_type_str, ans_item_no_type)
- local_ans_no2, ans_no_idx2 = get_right_no((ans_no_idx1, ans_no1), 1)
- one_type_no2 = one_type_no.copy()
- one_type_no2.extend(local_ans_no2)
- # print('one_type_no2:', one_type_no2)
- if len(one_type_no2) != one_type_num:
- # 题号前不要求空格时,出错的概率大,最好限制下范围,在按换行获取的题号中对不连续的题号做这种操作!!!!
- # 有题型行的一般归类比较工整点,所以先不操作
- ans_no21, ans_no_idx21 = get_many_ans_no(one_type_str, ans_item_no_type, reget=1)
- local_ans_no3, ans_no_idx3 = get_right_no((ans_no_idx21, ans_no21), 1)
- one_type_no3 = one_type_no.copy()
- one_type_no3.extend(local_ans_no3)
- # print('one_type_no3:', one_type_no3)
- if len(one_type_no3) != one_type_num:
- print("第" + str(num + 1) + "大题(" + all_type[num], ")答案个数有问题!!!")
- is_amount_wrong = 1
- if 0<one_type_num-len(one_type_no1)<=2:
- one_item_split = [del_no(i, ans_item_no_type) for i in one_item_split]
- one_type_ans.extend(one_item_split)
- one_type_no = one_type_no1
- elif 0<one_type_num-len(one_type_no2)<=2:
- new_item_split = [del_no(one_type_str[i:j], ans_item_no_type) for i, j in
- zip(ans_no_idx2, ans_no_idx2[1:] + [None])]
- one_type_ans.extend(new_item_split)
- one_type_no = one_type_no2
- else:
- # 在one_type_no1, one_type_no2中取连续的最长题号作为最后的答案
- consecutive_no1 = get_consecutive_no(one_type_no1)
- consecutive_no2 = get_consecutive_no(one_type_no2)
- if len(consecutive_no1) >= len(consecutive_no2):
- one_type_no = one_type_no1
- one_item_split = [del_no(i, ans_item_no_type) for i in one_item_split]
- one_type_ans.extend(one_item_split)
- else:
- one_type_no = one_type_no2
- new_item_split = [del_no(one_type_str[i:j], ans_item_no_type) for i, j in
- zip(ans_no_idx2, ans_no_idx2[1:] + [None])]
- one_type_ans.extend(new_item_split)
- else:
- print("第三种题号切分方案")
- new_item_split = [del_no(one_type_str[i:j], ans_item_no_type) for i, j in
- zip(ans_no_idx3, ans_no_idx3[1:] + [None])]
- one_type_ans.extend(new_item_split)
- one_type_no = one_type_no3
- else:
- print("第二种题号切分方案")
- new_item_split = [del_no(one_type_str[i:j], ans_item_no_type) for i, j in
- zip(ans_no_idx2, ans_no_idx2[1:] + [None])]
- one_type_ans.extend(new_item_split)
- one_type_no = one_type_no2
- else:
- print("第一种题号切分方案")
- one_item_split = [del_no(i, ans_item_no_type) for i in one_item_split]
- one_type_ans.extend(one_item_split)
- one_type_no = one_type_no1
- # --------------------------------------------------------------------------------------------
- print("第" + str(num + 1) + "大题(" + all_type[num], ")答案题号:", one_type_no)
- # print('答案:', one_type_ans)
- # ------------------------------------题目和答案组合---------------------------------------------------
- # 按题号进行组合
- if not is_amount_wrong:
- if one_type_ans:
- print('one_type_no:',one_type_no)
- print('one_type_ans:', one_type_ans)
- for k, one_item in enumerate(one_type_ans):
- # temp_id = item_id + type_id # 当前答案在整个答案中的序号,此方法不好
- if len(one_type_no) == len(one_type_ans):
- temp_id = -1
- # # ----------当前答案序号与题号对不上时------
- # if item_res[temp_id]["item_id"] != one_type_no[k]:
- # # 从试题的res寻找与当前答案题号相同的题目的位置
- temp_id_list = [i for i, v in enumerate(item_res) if v["item_id"] == one_type_no[k]]
- if len(temp_id_list) == 1:
- temp_id = temp_id_list[0]
- elif len(temp_id_list) > 1:
- for j in temp_id_list:
- if "key" not in item_res[j].keys():
- temp_id = j
- #--------------------end------------------
- if temp_id != -1:
- res_con = item_res[temp_id]['stem']
- if one_item.strip().upper() in ["A", "B", "C", "D", "E"]:
- item_res[temp_id].update({'parse': "", 'key': one_item.strip().upper()})
- else:
- item_res[temp_id].update(
- only_parse_split(one_item, all_type[num], res_con)) # 单道答案的结构化
- item_id += 1
- else:
- for k, one_item in enumerate(one_type_ans):
- temp_id = "no"
- # 从试题的res寻找与当前答案题号相同的题目的位置
- temp_id_list = [i for i, v in enumerate(item_res) if k<len(one_type_no) and v["item_id"] == one_type_no[k]]
- if len(temp_id_list) == 1:
- temp_id = temp_id_list[0]
- elif len(temp_id_list) > 1:
- for j in temp_id_list:
- if "key" not in item_res[j].keys():
- temp_id = j
- if temp_id != 'no': # 找到题目和答案相同的题目的序号时
- res_con = item_res[temp_id]['stem']
- item_res[temp_id].update(
- only_parse_split(one_item, all_type[num], res_con)) # 单道答案的结构化
- item_id += 1
- type_id += item_id
- new_ans_no.extend(one_type_no)
- # ---------------------------------------------------
- # except:
- # rd1_is_fail = 1
- else:
- rd1_is_fail = 1
- return item_res, rd1_is_fail
- def get_table_ans(ans_str, bf_all_no, flag=0):
- """
- 获取表格中的答案
- flag=1:返回表格开始位置
- bf_all_no:ans_str之前所有题号
- :return:
- """
- table_ans = []
- ans_no = []
- st = -1
- if ans_str and "table" in ans_str: # 答案以表格形式呈现, 表格应放在前两行位置,不要插在答案中间
- row_list = [] # 要求表格形式为 横纵分明 ,不存在合并
- for one_table in re.finditer('<table>(((?!(</?table>)).)*)</table>', ans_str, re.S):
- st = one_table.start()
- for tt in re.finditer(r'<tr>(((?!(</?tr>)).)*)</tr>', one_table.group(1), re.S):
- tt_list = re.split(r'</p></td>|<td><p>|</td><td>|</td>|<td>', tt.group(1))
- # row_list.append([col for col in tt_list if col.strip()]) # 也有可能答案为空
- row_list.append(tt_list)
- if row_list:
- print("^^^^^^存在答案放在表格里的情况!^^^^^^^")
- if len(row_list) % 2 != 0:
- print('有表格形式呈现的答案不是偶数行')
- if flag == 2:
- if "题号" in row_list[0] and len(row_list)>1:
- row_list = [re.sub("^\s*([1-9]|[1-2][0-9])\s*([((]\s*\d{1,2}\s*分?\s*[))])?\s*$", r"\n\1、", v)
- for row in row_list[1:] for v in row]
- return " ".join(row_list)
- else:
- row_list = [" ".join(row) for row in row_list]
- return "\n".join(row_list)
- if re.search("分值", "".join(row_list[-1][:3])):
- row_list = row_list[:-1]
- if len(row_list) % 2 == 0:
- if flag == 2:
- if "题号" in row_list[0] and len(row_list)>1:
- row_list = [re.sub("^\s*([1-9]|[1-2][0-9])\s*([((]\s*\d{1,2}\s*分?\s*[))])?\s*$", r"\n\1、", v)
- for row in row_list[1:] for v in row]
- return " ".join(row_list)
- else:
- row_list = [" ".join(row) for row in row_list]
- return "\n".join(row_list)
- for k, v in enumerate(row_list):
- if (k + 1) % 2 == 1: # 奇数行==》答案序号行
- # item_no = [int(i.strip()) if re.sub(r"[^\d]", "", i.strip()) else -1 for i in v]
- # item_no_st = [num for num, i in enumerate(item_no) if i != -1] # 可能开头是-1
- # # print(item_no_st)
- # ans_no.extend([i for i in item_no if i != -1]) # 表格序号
- # table_ans.extend(row_list[k + 1][item_no_st[0]: item_no_st[-1] + 1]) # 表格答案
- # --------------------
- item_no = []
- item_ans = []
- # special_item_no = [] # 特殊的题号 如14(1)
- for num, i in enumerate(v):
- if re.sub(r"[^\d]", "", i.strip()):
- no_info = re.match("(\d+)",i.strip())
- no = no_info.group(1) if no_info else 0
- special_no_info = re.match("(\d+)\s*([((\-_]\s*\d|[((\-_]?\s*[①②③④])", i.strip())
- if special_no_info:
- no = special_no_info.group(1)
- # special_item_no.append(int(i))
- if not item_no or int(no) != item_no[-1]:
- item_no.append(int(no))
- item_ans.append(row_list[k + 1][num])
- elif item_no and int(no) == item_no[-1]:
- item_ans[-1] += "#"+row_list[k + 1][num]
- else:
- if not bf_all_no or (item_no and 1 <= int(no) - item_no[-1] <= 2) or \
- (not item_no and bf_all_no and 1 <= int(no) - bf_all_no[-1] <= 2):
- item_no.append(int(no))
- if k+1 < len(row_list) and num < len(row_list[k + 1]):
- item_ans.append(row_list[k + 1][num])
- else:
- item_ans.append("")
- ans_no.extend(item_no)
- table_ans.extend(item_ans)
- if flag:
- return ans_no, table_ans, st
- return ans_no, table_ans
- def only_parse_split(one_item_ans, item_type, res_con, reparse_n=1):
- """
- 拆分出答案和解析,主要针对答案页中的每个题的答案进行拆分
- :one_item_ans: 单道题的答案解析部分,
- :reparse_n == 1:表示再解析
- :return:{'key': ,"parse": }
- """
- one_item_ans = re.sub("\n\s*(化学|物理|生物|和|与)+\s*【答案】\s*$", '', one_item_ans)
- dd = {'parse': one_item_ans, 'key': ""}
- if "选修" in one_item_ans.replace(" ", "")[:10] or \
- re.search("[((][12][))]\s【(解析|答案)】", one_item_ans.replace(" ", "")): # 2021-5-24
- return dd
- temp_ans = one_item_ans
- one_item_ans = one_item_ans.split("【答案】", maxsplit=1) # 答案关键字可能在后面
- if len(one_item_ans) == 2 and "【解析】" in one_item_ans[0]:
- one_item_ans = temp_ans
- else:
- one_item_ans = one_item_ans[-1]
- simp_item = re.sub(r"(【([解分][析答]|详解|点[评睛])】|答案|解析|详解)\s*[::]?", "", one_item_ans)
- simp_item = re.sub("[^\u4e00-\u9fa5∵∴]", "", simp_item)
- # deng_num = re.findall(r"((?!(src|width|height|style)).)+?([==]).+?", one_item_ans, re.S)
- tempitem = re.sub("(src|width|height|style)[==]", "", one_item_ans)
- deng_num = re.findall(r"([==]).+?", tempitem, re.S)
- huanheng_num = re.findall("\n+", one_item_ans, re.S)
- if len(simp_item) < 10 and re.search("因为?|因此|所以|根据|依据|若|假设", simp_item) is None and len(deng_num) < 2:
- dd['parse'] = ""
- if len(huanheng_num) > 1:
- dd['parse'] = one_item_ans
- sim_parse = dd['parse'] # 去掉点评后用于找答案
- if re.search(r"【(解析|解答|分析|详解|点评|点睛)】\n?|(解析|解答|分析|(?<!联)详?解|点评|点睛)\s*[::]", one_item_ans):
- dd1 = dict(zip(["key", "parse_title", "parse"],
- re.split(r"【(解析|解答|分析|详解|点评|点睛)】\n?", one_item_ans, maxsplit=1)))
- if len(dd1)==1:
- dd1 = dict(zip(["key", "parse_title", "parse"],
- re.split(r"(解)\s*[::]", one_item_ans, maxsplit=1)))
- if "【答案】" in temp_ans:
- dd["key"] = dd1["key"]
- if len(dd1) >= 3:
- dd["parse"] = "【" + dd1["parse_title"] + "】" + dd1["parse"]
- del dd1["parse_title"]
- return dd
- if len(dd1) >= 3:
- dd["key"] = dd1["key"]
- dd["parse"] = "【" + dd1["parse_title"] + "】" + dd1["parse"]
- del dd1["parse_title"]
- return dd
- sim_parse = re.split("【点评】|【点睛】", dd["parse"])[0].strip()
- # 将解析中末尾出现的图片去掉
- while re.search('\n\s*<imgsrc\d+\sw_h=(\d+\*\d{3})/>\s*$', sim_parse):
- sim_parse = re.sub('\n\s*<imgsrc\d+\sw_h=(\d+\*\d{3})/>\s*$', "", sim_parse)
- if item_type.replace("题", "") in ["单选", "多选", "选择", "不定选择"]:
- ans = re.search(r'故选择?\s*[::]?\s*<imgsrc\d+\sdata-latex="\$?([A-Z;;和与、、\s]+)\$?"/>'
- r'|故选择?\s*[::]?\s*([A-Z;;和与、、\s]+)', dd["parse"].replace("$", ""))
- ans1 = re.search(r'故答案[为是有]\s*[::]\s*<imgsrc\d+\sdata-latex="\$?([A-Z;;和与、、\s]+)\$?"/>'
- r'|故答案[为是有]\s*[::]?\s*([A-Z;;和与、、\s]+)', dd["parse"].replace("$", ""))
- if ans:
- dd["key"] = ans.group(1) if ans.group(1) is not None else ans.group(2)
- if ans1:
- dd["key"] = ans1.group(1) if ans1.group(1) is not None else ans1.group(2)
- elif not dd['key']:
- dd['key'] = one_item_ans.strip()
- if dd['parse']:
- dd['key'] = "见解析"
- dd['key'] = re.sub(r"[.;;.]\s*$", "", dd['key'])
- elif re.search("证明|求证", res_con):
- dd['key'] = "见解析"
- elif item_type: # 把所有的图片能先提前替换比较好,后面匹配的话会容易些
- ans0 = re.search(r'故选\s*[::]?\s*([A-Z;;和与、、\s]+)[..;;。]?$', sim_parse) # 试验题中可能还有选择题
- ans01 = re.search(r'故选\s*[::]\s*<imgsrc\d+\sdata-latex="\$?([A-Z;;和与、、\s]+)\$?"/>', sim_parse) # 可能开始题型写错
- ans1 = re.search(r'(故|因[而此]|所以)\s*[::]?\s*(答案分?别?[为是填]?|填)\s*[::]?\s*(((?!(<img)).)+?)[..]?\s*(\n|$)', sim_parse)
- ans11 = re.search(r'((?<!解)答\s*[::]|整理得\s*[::]?)\s*(.+?)([..;;]?\s*$|[..]\s*\n)', sim_parse)
- ans2 = re.search(r'(故|因[而此]|所以)\s*[::]?\s*(答案分?别?[为是填]?|填)\s*[::]?\s*(<imgsrc.+?/>)[..]?\s*(\n|$)', sim_parse, re.S)
- ans22 = re.search(r'(故|因[而此]|所以)\s*[::]?\s*(答案分?别?[为是填]?|填)\s*[::]?\s*([^∴∵故因所即【】]+?)([..]\s*(\n|$)|$)', sim_parse)
- ans21 = re.search(r'综上所述\s*[::]\s*([^∴∵故因所即【】]+?)[..;;]\s*$', sim_parse)
- ans3 = re.search(r'(故|因[而此]|所以|∴)\s*[::]?.+?[为是填]\s*[::]?\s*([^∴∵故因所即则【】]+?)([..;;,,]\s*$|[..]\s*\n)', sim_parse) # 改添
- ans31 = re.search(r'(故|因[而此]|所以|∴)\s*([^当为是填∴∵因所故即则【】]+?)[..;;]\s*$', sim_parse) # 改添
- ans32 = re.search(r'(故|因[而此]|所以)\s*[::]?[^当为是填∴∵因所故即【】]+?[为是填]\s*[::]?\s*(<imgsrc.+?/>)[..]?\s*(\n|$)', sim_parse, re.S)
- ans4 = re.search(r'\n\s*[==]([^=\n]+?)[..]?\s*$', sim_parse)
- # ans42 = re.search(r'[==](?!")(((?!([故=∴即]|原式|因[而此]|所以|\n|=[^"])).)+?)[..]?\s*$', sim_parse)
- ans41 = re.search(r'原式\s*[==].+?[==](?!")(((?!(=|=[^"])).)+?|\s*<imgsrc.+?/>)([..]?\s*$|[..]\s*\n)', sim_parse)
- ans42 = re.search("解集?[得为::]+?\s*(\$.+?)$|[::]\s*(\$.+?)$", one_item_ans)
- if reparse_n != 2 and "【答案】" not in one_item_ans and dd['parse'] and \
- len(re.findall(r"[((]\d[))]|[\n::;;。】]([((](i{1,3}|[ⅰⅱⅲⅳⅠⅡⅢIV①②③④])[))]|[①②③④]\s*(?![+\-]))",
- sim_parse.replace(" ", ""))) > 1 and not (item_type == '填空题' and len(re.findall(r"_{2,}|_+([^_]*?)_+", res_con)) == 1):
- dd["key"] = "见解析"
- elif ans0:
- dd["key"] = ans0.group(1)
- elif ans01:
- dd["key"] = ans01.group(1)
- elif ans1 or ans11:
- dd["key"] = ans1.group(3) if ans1 else ans11.group(2)
- elif ans2:
- dd["key"] = ans2.group(3)
- elif ans22:
- dd["key"] = ans22.group(3)
- elif ans21:
- dd["key"] = ans21.group(1)
- elif (ans3 or ans31 or ans32) and '证明' not in one_item_ans:
- if ans3:
- dd["key"] = ans3.group(2)
- if ans31:
- dd["key"] = ans31.group(2)
- speci_key_info = re.search("解集?[得为::]+?\s*(\$.+?)$|[::]\s*(\$.+?)$", dd["key"])
- if speci_key_info:
- dd["key"] = speci_key_info.group(1) if speci_key_info.group(1) else speci_key_info.group(2)
- if ans32:
- dd["key"] = ans32.group(2)
- elif ans42:
- dd["key"] = ans42.group(1) if ans42.group(1) else ans42.group(2)
- if not dd["parse"]:
- dd["parse"] = one_item_ans
- elif (ans4 or ans41) and '证明' not in one_item_ans:
- if ans4:
- dd["key"] = ans4.group(1)
- if ans41:
- dd["key"] = ans41.group(1)
- # if ans42:
- # dd["key"] = ans42.group(1)
- elif not re.sub("[\s略解析【】]", "" ,dd['parse']):
- dd['key'] = one_item_ans.strip()
- else:
- if dd["key"]:
- dd['parse'] = dd["key"] + dd['parse']
- dd["key"] = "见解析"
- else: # 题型未知
- if len(simp_item) < 10:
- dd["key"] = re.sub(r"【答案】|答案\s*[::]", "", one_item_ans.strip())
- else:
- ans1 = re.search(
- r'故答?案?选择?\s*[::]\s*<imgsrc\d+\sdata-latex="([A-Z;;和与、、\s]+)"/>|故答?案?选择?\s*[::]?\s*([A-Z;;和与、、\s]+)',
- dd["parse"].replace("$", ""))
- ans2 = re.search(r'故\s*[::]?\s*答案分?别?[为是]?\s*[::]?\s*(.+?)[..]\s*(\n|$)', dd["parse"])
- ans3 = re.search(r'(【答案】|答案)\s*[::]?(.+?)(\n|$)', dd["parse"])
- if ans1:
- dd["key"] = ans1.group(1) if ans1.group(1) is not None else ans1.group(2)
- elif ans2:
- dd["key"] = ans2.group(1)
- elif ans3:
- dd["key"] = ans3.group(2)
- dd["parse"] = dd["parse"].replace(ans3.group(0), "")
- elif not dd['key']:
- dd['key'] = "见解析"
- # print('最后:',dd)
- return dd
- def ans_structure_step1(anss, item_type_classify, item_res):
- """
- 针对答案部分解析结构化汇总
- anss : 整个答案部分
- :return: dd = {'parse': , 'key': }
- """
- anss = [k for k in anss if k.strip()]
- ans_label = [k for k, a in enumerate(anss) if re.match("【答案】", a.strip())]
- parse_label = [k for k, a in enumerate(anss) if re.match("【解析】", a.strip())]
- if len(ans_label) == 1 and len(parse_label) == 1:
- try:
- ans1 = anss[ans_label[0] + 1: parse_label[0]]
- parse1 = anss[parse_label[0]+1:]
- item_res = ans_structure_step2(ans1, item_type_classify, item_res,'group_ans')
- item_res = ans_structure_step2(parse1, item_type_classify, item_res, 'group_parse')
- except:
- item_res = ans_structure_step2(anss, item_type_classify, item_res)
- else:
- item_res = ans_structure_step2(anss, item_type_classify, item_res)
- return item_res
- def ans_structure_step2(anss, item_type_classify, item_res, *group):
- """
- 拆分答案,并根据已拆分好的题目item_res 补上答案和解析
- 有的答案放在表格里,如选择题、填空题、判断题,有的一行多个答案
- 思路:1.先按一行没有多个题答案的情况取答案,数量与题干不同 时 >>>> 2.再按一行多个答案的情况取答案:
- 1)先判断表格,拿到表格的答案;2)一行多个答案
- anss: 一组按所有不重复题号的答案
- item_type_classify: 题目中对各题型的统计
- :return: [{'parse': , 'key': },{},{}]
- """
- while not anss[0]:
- anss = anss[1:]
- if re.match(".+?省.+?试[卷题]|[^a-zA-Z]*?【专题】", anss[0]):
- anss = anss[1:]
- # --------- 答案整体解析----存在一行中有选择题和填空题答案,填空题答案尽量每题占一行----------
- item_type_num = sum(list(item_type_classify.values()))
- all_item_ans = [] # 前期只记录表格答案和排列型答案
- table_ans = []
- ans_no = [] # 只记录表格答案和排列型答案的id
- # 默认表格答案放在最前面 !!!
- while anss and "table" in anss[0]: # 答案以表格形式呈现, 表格应放在前两行位置,不要插在答案中间
- row_list = [] # 要求表格形式为 横纵分明 ,不存在合并
- for tt in re.finditer('<tr>(((?!(</?tr>)).)*)</tr>', anss[0], re.S): # 先划分每行
- tt_list = re.split(r'</p></td>|<td><p>|</td><td>|</td>|<td>', tt.group(1)) # 再划分每列
- # row_list.append([col for col in tt_list if col.strip()]) # 也有可能答案为空
- row_list.append(tt_list)
- if row_list:
- print("^^^^^^存在答案放在表格里的情况!^^^^^^^")
- is_other_table = False
- if len(row_list) % 2 != 0:
- print('表格形式呈现的答案不是偶数行')
- # 可能是填空题放在表格里,可以先去表格看看
- if "题号" in row_list[0] and len(row_list) > 1:
- row_list = [re.sub("^\s*([1-9]|[1-2][0-9])\s*([((]\s*\d{1,2}\s*分?\s*[))])?\s*$", r"\n\1、", v)
- for row in row_list[1:] for v in row]
- anss[0] = "\n" + " ".join(row_list)
- is_other_table = True
- elif re.search("^\s*([1-9]|[12][0-9])\s*[..、、::].+?", "".join(row_list[0])):
- temp_id = re.search("^\s*([1-9]|[12][0-9])\s*[..、、::].+?", "".join(row_list[0])).group(1)
- if ans_no and 1 <= int(temp_id) - ans_no[-1] <= 2:
- # anss[0] = re.sub(r'</?table>|</?p>|</?t[dr]>|</?tbody>', '', anss[0])
- anss[0] = "\n" + "\n".join(["".join(i) for i in row_list])
- is_other_table = True
- else:
- print("row_list:", row_list)
- # if "题号" in row_list[0] and len(row_list) > 1:
- # row_list = [re.sub("^\s*([1-9]|[1-2][0-9])\s*([((]\s*\d{1,2}\s*分?\s*[))])?\s*$", r"\n\1、", v)
- # for row in row_list[1:] for v in row]
- # anss[0] = "\n" + " ".join(row_list)
- for k, v in enumerate(row_list):
- # print('-----',v)
- if (k + 1) % 2 == 1: # 奇数行==》答案序号行
- # item_no = [int(i) if re.sub(r"[^\d]", "", i) else -1 for i in v]
- # item_no_st = [num for num, i in enumerate(item_no) if i != -1] # 可能开头是-1
- # ans_no.extend([i for i in item_no if i != -1]) # 表格序号
- # table_ans.extend(row_list[k + 1][item_no_st[0]: item_no_st[-1] + 1]) # 表格答案
- # ----------------------------
- item_no = []
- item_ans = []
- # special_item_no = [] # 特殊的题号 如14(1)
- for num, i in enumerate(v):
- if re.sub(r"[^\d]", "", i.strip()):
- no_info = re.match("(\d+)", i.strip())
- no = no_info.group(1) if no_info else 0
- special_no_info = re.match(r"(\d+)\s*([((\-_]\s*\d|[((\-_]?\s*[①②③④])", i.strip())
- if special_no_info:
- no = special_no_info.group(1)
- # special_item_no.append(int(i))
- if not item_no or int(no) != item_no[-1]:
- item_no.append(int(no))
- item_ans.append(row_list[k + 1][num])
- elif item_no and int(no) == item_no[-1]:
- item_ans[-1] += "#" + row_list[k + 1][num]
- else:
- if (not ans_no and int(no)) or (item_no and 1 <= int(no) - item_no[-1] <= 2) or \
- (not item_no and ans_no and 1 <= int(no) - ans_no[-1] <= 2):
- item_no.append(int(no))
- if k + 1 < len(row_list) and num < len(row_list[k + 1]):
- item_ans.append(row_list[k + 1][num])
- else:
- item_ans.append("")
- ans_no.extend(item_no)
- table_ans.extend(item_ans)
- if not is_other_table:
- anss = anss[1:]
- print("表格答案:", table_ans)
- all_item_ans.extend(table_ans)
- if anss and re.search("<table>.*?</table>", anss[0], re.S) is None:
- anss[0] = anss[0].split("</table>")[-1].replace("</div>", "")
- #======= 先按一行没有多个题答案的情况取答案=======
- anss_str = table_label_cleal("\n" + "\n".join(anss)) if anss else ""
- # print(anss_str)
- ans_item_no_type = 1 # 初步定义答案的题号就是第一种类型!!!
- # 将序号前面是大写字母或分号的情况,加空
- anss_str = re.sub(r"([A-H])\s*[..](\s*([1-9][0-9]|[1-9])\s*[..、、])", r"\1 \2", anss_str)
- while re.search(r"([A-E])(([1-9][0-9]|[1-9])\s*[..、、]\s*[A-E])", anss_str):
- anss_str = re.sub(r"([A-E])(([1-9][0-9]|[1-9])\s*[..、、]\s*[A-E])", r"\1 \2", anss_str)
- def sub1(ss):
- if int(ss.group(3)) - int(ss.group(1)) == 1:
- return ss.group(1)+ss.group(2)+' '+ss.group(3)+'、'+ss.group(4)
- anss_str = re.sub(r"([1-9][0-9]|[1-9])\s*([..、、]\s*[A-E])\s*([1-9][0-9]|[1-9])\s*([A-E]\s*([1-9][0-9]|[1-9])\s*[..、、])", sub1, anss_str)
- anss_str = re.sub(r"([;;])(\s*([1-9][0-9]|[1-9])\s*[.、、])", r"\1 \2", anss_str)
- def sub2(ss):
- if int(ss.group(3)) - int(ss.group(2)) in [1, 2]:
- return ss.group(1)+"\n"+ss.group(3)+"、"+ss.group(4)
- else:
- return ss.group(0)
- anss_str = re.sub(r"(\n\s*([1-9][0-9]|[1-9])\s*[..、、].+?)\n([1-9][0-9]|[1-9])\s*(?![..、、])([^\s\d]+)", sub2, anss_str, flags=re.S)
- anss_str = re.sub("\n\s*(\${*?)([1-9][0-9]|[1-9])\s*([..、、])(.+?)", r"\n\2\3\1\4", anss_str)
- anss_str = re.sub("\$(([1-9][0-9]|[1-9])\s*[..、、].+?)", r"$ \1", anss_str)
- anss_str = re.sub("(\${*?)([1-9][0-9]|[1-9])\s*([..、、])\s*(?!\d)", r" \2\3\1", anss_str)
- # print(anss_str)
- item_no_info = pre_get_item_no('\n' + anss_str, ans_item_no_type) # 按\n\d、
- print("初步题号:", item_no_info) # 初步按非表格非排列的形式获取题号信息
- if not item_no_info and len(anss_str.replace(" ", "")) < 50:
- item_0 = re.split(r"[1-9]\s*[..、、::]|[1-9][0-9]\s*[..、、::]", anss_str)
- if len(item_0) > 1:
- anss_str = item_0[0]
- array_ans_no, array_ans = get_array_ans(anss_str, ans_no, item_res[0]['item_id'])
- all_item_ans.extend(array_ans)
- ans_no.extend(array_ans_no)
- if len(item_0) > 1:
- all_item_ans.extend(item_0[1:])
- ans_no.extend(re.findall(r"([1-9]|[1-9][0-9])\s*[..、、::]", anss_str))
- if len(ans_no) == item_type_num or len(ans_no) == len(item_res): # 只有表格答案或排列答案的情况
- print('答案第1种切分方案:只有表格答案或排列答案的情况!')
- item_res = get_ans_match(item_res, all_item_ans, ans_no, group)
- else:
- is_new_no = 0
- if not item_no_info:
- item_no_info = pre_get_item_no('\n' + anss_str, ans_item_no_type, flag=1)
- if item_no_info: # 这里新更新的item_no_info放到和下面一起处理,不严谨
- is_new_no = 1
- ans_no0, ans_no_idx0 = get_right_no(item_no_info) # 初始题号纠正,第一个不换行的题号可能被剔除
- print("ans_no0:", ans_no0)
- print("ans_no_idx0:", ans_no_idx0)
- is_from_0 = 1 # shi
- if ans_no0 and ans_no_idx0[0] != 0 and ans_no0[0] > 1:
- is_all_img = re.match("(<imgsrc((?!/>).)*?/>[\s\n]*)*?$", anss_str[:ans_no_idx0[0]].strip(),re.S)
- if not is_all_img:
- ans_no_idx0.insert(0, 0)
- is_from_0 = 0 # fei
- # 除表格、排列型之外的答案
- rest_item_split = [('\n' + anss_str)[i:j] for i, j in zip(ans_no_idx0, ans_no_idx0[1:] + [None])]
- if not is_from_0: # 不是从0开始, 从0开始的话就不用判断
- if re.match('(\n|^)故[::]?选[::]|故[::]?答案分?别?[为是]?'
- '|【([解分][析答]|详解|点[评睛])】|(答案|解析|详解)[::]',
- rest_item_split[0].replace(" ", "")) is None:
- if item_no_info[0][0]==0 or item_no_info[0][1]=='1':
- # 说明rest_item_split[0] 是一行多个排列的答案
- array_ans_no, array_ans = get_array_ans(rest_item_split[0], ans_no, item_res[0]['item_id'], ans_no0[0])
- if array_ans:
- ans_no.extend(array_ans_no)
- all_item_ans.extend(array_ans)
- rest_item_split = rest_item_split[1:]
- ans_no_idx0 = ans_no_idx0[1:]
- else:
- print("rest_item_split[0]:", rest_item_split[0])
- # 找出非选择题的切分点
- item_0 = re.split(r"([1-9]\s*[..、、::]\s*(?![A-F])|[1-9][0-9]\s*[..、、::]\s*(?![A-F]))", rest_item_split[0], maxsplit=1)
- if len(item_0) > 1: # 存在这样的切分点
- ans_no_idx0.insert(1, re.search(r"([1-9]|[1-9][0-9])\s*[..、、::]\s*(?![A-F])",
- rest_item_split[0]).start())
- rest_item_split[0] = item_0[0]
- rest_item_split.insert(1, "\n" + "".join(item_0[1:])) # 加了一个,题号和索引也要加一个
- ans_no0.insert(0, int(re.findall("[1-9][0-9]|[1-9]", item_0[1])[0])) # 这时补充的肯定与后面序号差别比较大
- # info0 = re.search(r"([1-9]|[1-4][0-9])\s*[..、、::]\s*(?![A-F])", rest_item_split[0]) # 有问题吧
- info0 = re.search(r"([1-9]|[1-9][0-9])\s*[..、、::]\s*(?![A-F])", rest_item_split[0])
- if info0: # ans_no0比len(rest_item_split)少
- ans_no_idx0[0] = info0.start()
- array_ans_no, array_ans = get_array_ans(rest_item_split[0], ans_no, item_res[0]['item_id'], ans_no0[0])
- if array_ans:
- ans_no.extend(array_ans_no)
- all_item_ans.extend(array_ans)
- else:
- ans_no_idx0 = ans_no_idx0[1:]
- if 'imgsrc' in rest_item_split[0]: # 针对答案前面存在图的情况,图暂时不管(不清楚是什么图)
- temp_str0 = re.sub('<imgsrc.*?/>', "", rest_item_split[0]).replace(" ", "")
- if len(temp_str0) < 3 and ans_no0 and ans_no0[0] > 9:
- is_from_0 = 1
- rest_item_split = rest_item_split[1:]
- # 更新anss_str
- # anss_str = "\n" + "\n".join(rest_item_split[1:]) # 前面已截取,这里又截取,不对吧
- anss_str = "\n" + "\n".join(rest_item_split) # 2021-9-16
- else:
- ans_no0.insert(0, ans_no0[0] - 1)
- if is_new_no:
- ans_no0, rest_item_split = get_seq_no(ans_no0, rest_item_split)
- ans_no.extend(ans_no0)
- all_item_ans.extend(rest_item_split)
- item_res = get_ans_match(item_res, all_item_ans, ans_no, group)
- else:
- print("ans_no:::",ans_no) # ans_no只记录表格答案和排列型答案
- print("::::", ans_no0, ans_no_idx0)
- pre_split_ansinfo_list = all_item_ans, ans_no, ans_no0, ans_no_idx0, anss_str, is_from_0, ans_item_no_type
- all_item_ans, ans_no = ans_select(item_res, item_type_num, rest_item_split, pre_split_ansinfo_list)
- item_res = get_ans_match(item_res, all_item_ans, ans_no, group)
- return item_res
- def get_array_ans(one_item, raw_ans_no, st_no, af_no=0, temp_type=""):
- """
- 获取排列型的答案
- :param one_item: 获取排列型的答案的文本
- :param raw_ans_no: 已有的答案id
- :param st_no: 题文中的初始题号
- :param af_no: one_item后面题文中的初始题号
- :param temp_type: 题型
- :return:
- """
- one_item_no, one_item_ans = [], []
- if re.search("([1-9]|1[0-9])\s*[-~-~~~]\s*1?[0-9]\s*[::]?\s*([A-Zc]\s*){2,}", one_item):
- no_info = re.findall("([1-9]|1[0-9])\s*[-~~]\s*(1?[0-9])\s*[::]?\s*([A-Zc]\s*){2,}", one_item)
- no_list = [list(range(int(i[0]), int(i[1]) + 1)) for i in no_info]
- row_split = re.split("\n*[1-9]\s*[-~-~~~]\s*1?[0-9]|\n*1[0-9]\s*[-~-~~~]\s*1?[0-9]", one_item)
- if len(row_split) - len(no_list) == 1:
- if not row_split[0].strip():
- one_item_no.extend(sum(no_list, []))
- for k, j in enumerate(row_split[1:]):
- if len(re.findall("[A-Zc](?!\))", j)) == len(no_list[k]):
- one_item_ans.extend(re.findall("[A-Zc](?<!\))", j))
- elif len(re.split("\s+", j.strip())) == len(no_list[k]):
- one_item_ans.extend(re.split("\s+", j.strip()))
- elif len(re.split("[、、]+", j.strip())) == len(no_list[k]):
- one_item_ans.extend(re.split("[、、]+", j.strip()))
- elif re.search("\d", j): # 存在1-8AAADS 9.A 10.B 的情况
- new_rows = re.split("([1-9]|[1-9][0-9])\s*[..、、::]?\s*(?=[A-F])", j)
- if len(new_rows)>2:
- if len(re.findall("[A-Zc](?!\))", new_rows[0])) == len(no_list[k]):
- one_item_ans.extend(re.findall("[A-Zc](?<!\))", new_rows[0]))
- elif len(re.split("\s+", new_rows[0].strip())) == len(no_list[k]):
- one_item_ans.extend(re.split("\s+", new_rows[0].strip()))
- elif len(re.split("[、、]+", new_rows[0].strip())) == len(no_list[k]):
- one_item_ans.extend(re.split("[、、]+", new_rows[0].strip()))
- for jn, jv in enumerate(new_rows[1:]):
- if not (jn+2)%2: # 偶数位
- one_item_no.append(int(jv))
- one_item_ans.append(new_rows[jn+1+1])
- elif no_list[0][0] > 1:
- tt0 = re.split("\s+", row_split[0].strip())
- if len(tt0) < no_list[0][0] - 1:
- tt0 = re.findall("[A-Zc](?!\))", row_split[0])
- if len(tt0) >= no_list[0][0] - 1:
- one_item_ans.extend(tt0[-(no_list[0][0] - 1):])
- one_item_no.extend(list(range(1, no_list[0][0]))[-(no_list[0][0] - 1):])
- one_item_no.extend(sum(no_list, []))
- for k, j in enumerate(row_split[1:]):
- print(re.split("\s+", j.strip()))
- if len(re.findall("[A-Zc](?!\))", j)) == len(no_list[k]):
- one_item_ans.extend(re.findall("[A-Zc](?<!\))", j))
- elif len(re.split("\s+", j.strip())) == len(no_list[k]):
- one_item_ans.extend(re.split("\s+", j.strip()))
- elif len(re.split("[、、]+", j.strip())) == len(no_list[k]):
- one_item_ans.extend(re.split("[、、]+", j.strip()))
- elif (re.search("([1-9]|1[0-9])\s*[A-Zc]", one_item) and temp_type.replace("题", "")
- in ['选择', '单选', '多选', '不定选择']) or re.search("^[\d\sA-Zc..、、\n]+$", one_item): # 1A 2B 3C 4D
- row_ans = re.split("[1-9][0-9]|[1-9]", one_item)
- if re.search("[A-Fc]", row_ans[0].strip()):
- new_ans = re.findall("[A-Zc](?<!\))", row_ans[0])
- one_item_ans.extend(new_ans)
- if raw_ans_no:
- one_item_no.extend(list(range(raw_ans_no[-1] + 1, raw_ans_no[-1] + 1 + len(new_ans))))
- else:
- one_item_no.extend(list(range(st_no, 1 + len(new_ans))))
- else:
- row_ans = row_ans[1:]
- one_item_ans.extend(row_ans)
- one_item_no.extend([int(i) for i in re.findall(r"[1-9][0-9]|[1-9]", one_item)])
- else:
- # row_ans = sum([re.findall("[A-Z](?<!\))", str(k.group())) for k in re.finditer("[A-Z]{4,}", one_type)],[])
- row_no1, row_ans_idx1 = get_many_ans_no("\n" + one_item, 1)
- row_no1, row_ans_idx1 = get_right_no((row_ans_idx1, row_no1), 1) # 筛选
- row_ans1 = [del_no(("\n" + one_item)[i:j]) for i, j in
- zip(row_ans_idx1, row_ans_idx1[1:] + [None])] if len(row_ans_idx1) > 1 else []
- row_ans2 = re.findall("[A-Zc](?<!\))", one_item)
- row_ans, row_no = [], []
- if af_no and len(row_ans1) in [af_no - 1, af_no - 2]:
- one_item_ans.extend(row_ans1)
- one_item_no.extend(row_no1)
- else:
- if af_no and len(row_ans1) > 5 and len(row_ans2) - len(row_ans1) > 2 and len(row_ans2) - af_no > 2:
- one_item_ans.extend(row_ans1)
- one_item_no.extend(row_no1)
- else:
- temp_item = re.sub("<imgsrc.*?/>", "", one_item).strip()
- if len(re.findall("[\u4e00-\u9fa5]", temp_item))<2: # 尽量没有中文
- row_ans = row_ans2
- one_item_ans.extend(row_ans)
- if raw_ans_no and row_ans:
- one_item_no.extend(list(range(raw_ans_no[-1] + 1, raw_ans_no[-1] + 1 + len(row_ans))))
- else:
- one_item_no.extend(list(range(1, 1 + len(row_ans))))
- return one_item_no, one_item_ans
- def ans_select(item_res, item_type_num, rest_item_split, pre_split_ansinfo_list):
- """
- 按换行切分答案、按一行多个答案(含答案序号前有空格或非空格两种情况),
- 按此三种方法,与题文试题的切分结构进行对比而选取答案
- :param item_type_num:
- :param ans_no:
- :param ans_str:
- :return:
- """
- all_item_ans, ans_no, ans_no0, ans_no_idx0, anss_str, is_from_0, ans_item_no_type = pre_split_ansinfo_list
- ans_no1 = ans_no.copy()
- ans_no1.extend(ans_no0)
- # 先按换行格式获取答案(没有一行多个答案的情况)
- print("ans_no1:",ans_no1)
- print("item_type_num:",item_type_num)
- if len(ans_no1) != item_type_num and len(ans_no1) != len(item_res):
- if is_from_0 and len(ans_no1) > 1: # 答案确实只有部分或前面答案是图片形式==>有问题,1行多个答案的第1个答案也可能是从1开始!!!!
- print('答案第6种切分方案:答案确实只有部分或前面答案是图片形式!')
- # 先判断下是否连续,因为预先允许差一个;如果不连续,则进一步寻找后再切分
- seq_no = find_seq_num(ans_no1)
- if len(seq_no) > 1:
- rest_item_split = [del_no(k) for k in rest_item_split]
- all_item_ans.extend(rest_item_split)
- for num, s in enumerate(seq_no[1:]):
- if s[0] - seq_no[num][-1] == 2:
- que_no = s[0]-1
- last_idx = ans_no1.index(s[0]-2)
- new_split = re.split("(\s+|【fei】)"+str(que_no)+"\s*[..、、]",all_item_ans[last_idx], maxsplit=1)
- if len(new_split) == 3:
- all_item_ans[last_idx] = new_split[0]
- all_item_ans.insert(last_idx+1, new_split[2])
- ans_no1.insert(ans_no1.index(s[0]), que_no)
- else:
- rest_item_split = [del_no(k) for k in rest_item_split]
- all_item_ans.extend(rest_item_split)
- ans_no = ans_no1 # 2021-11-22
- else:
- # 存在一行多个的情况,题号前必须有空格
- temp_ans_no1, ans_no_idx1 = get_many_ans_no("\n" + anss_str, ans_item_no_type) # 初步获取
- temp_ans_no1, ans_no_idx1 = get_right_no((ans_no_idx1, temp_ans_no1), 1) # 筛选
- ans_no2 = ans_no.copy()
- ans_no2.extend(temp_ans_no1)
- print("ans_no2:", ans_no2)
- if len(ans_no2) != item_type_num and len(ans_no2) != len(item_res): # 一行多个,题号前可有可无空格
- # 题号前不要求空格时,出错的概率大,最好限制下范围,在按换行获取的题号中(在最后一个连续处中断,对前面不连续的题号做下面的操作)!!!!
- new_anss_str = "\n" + anss_str
- seq_no = find_seq_num(ans_no1)
- ans_no_after = []
- no_idx_after = []
- print("seq_no:",seq_no)
- if seq_no:
- if seq_no[-1][0] in ans_no0:
- ans_no_after.extend(ans_no0[ans_no0.index(seq_no[-1][0]):])
- no_idx_after.extend(ans_no_idx0[ans_no0.index(seq_no[-1][0]):])
- breakp = ans_no_idx0[ans_no0.index(seq_no[-1][0])]
- new_anss_str = ("\n" + anss_str)[:breakp]
- temp_ans_no21, ans_no_idx21 = get_many_ans_no(new_anss_str, ans_item_no_type, reget=1)
- temp_ans_no21.extend(ans_no_after)
- ans_no_idx21.extend(no_idx_after)
- temp_ans_no21, ans_no_idx21 = get_right_no((ans_no_idx21, temp_ans_no21), 1) # 筛选
- ans_no3 = ans_no.copy()
- ans_no3.extend(temp_ans_no21)
- print("ans_no3:", ans_no3)
- if len(ans_no3) != item_type_num and len(ans_no3) != len(item_res):
- # temp_ans_no22.extend(ans_no_after) # 不要
- # ans_no_idx22.extend(no_idx_after) # 不要
- # temp_ans_no22, ans_no_idx22 = get_right_no((ans_no_idx22, temp_ans_no22), 1) # 筛选
- # ans_no4 = ans_no.copy() # 不要
- # ans_no4.extend(temp_ans_no22) # 不要
- # print("ans_no4:", ans_no4) # 不要
- # if len(ans_no4) != item_type_num and len(ans_no4) != len(item_res):
- print('可能存在答案格式(无序号)影响答案个数有问题!!!', )
- # 也有可能题目比答案多,如理综题目不全
- if abs(len(item_res) - len(ans_no1)) <= 2 or (len(ans_no1) > len(item_res) and ans_no1[0] == 1):
- print('换行切分的答案个数与题目个数接近!!')
- rest_item_split = [del_no(k) for k in rest_item_split]
- all_item_ans.extend(rest_item_split)
- ans_no = ans_no1
- elif abs(len(item_res) - len(ans_no2)) <= 2 or (
- len(ans_no2) > len(item_res) and ans_no2[0] == 1):
- print('(换行+空格)切分的答案个数与题目个数接近!!', ans_no2)
- rest_item_split = [del_no(("\n" + anss_str)[i:j]) for i, j in
- zip(ans_no_idx1, ans_no_idx1[1:] + [None])]
- all_item_ans.extend(rest_item_split)
- ans_no = ans_no2
- else:
- # 在ans_no1, ans_no2中取连续的最长题号作为最后的答案
- consecutive_no1 = get_consecutive_no(ans_no1)
- consecutive_no2 = get_consecutive_no(ans_no2)
- if len(consecutive_no1) >= len(consecutive_no2):
- ans_no = ans_no1
- rest_item_split = [del_no(k) for k in rest_item_split]
- all_item_ans.extend(rest_item_split)
- else:
- ans_no = ans_no2
- rest_item_split = [del_no(("\n" + anss_str)[i:j]) for i, j in
- zip(ans_no_idx1, ans_no_idx1[1:] + [None])]
- all_item_ans.extend(rest_item_split)
- # elif all_item_ans: # 最后起码把表格答案、排列型答案先填上
- # item_res = get_ans_match(item_res, all_item_ans, ans_no, group)
- # else:
- # print('答案第5种切分方案:存在一行多个答案,每个答案题号前可以没有空格2')
- # rest_item_split = [del_no(("\n" + anss_str)[i:j]) for i, j in
- # zip(ans_no_idx22, ans_no_idx22[1:] + [None])]
- # all_item_ans.extend(rest_item_split)
- # ans_no = ans_no4
- else:
- print('答案第4种切分方案:存在一行多个答案,每个答案题号前可以没有空格')
- rest_item_split = [del_no(("\n" + anss_str)[i:j]) for i, j in
- zip(ans_no_idx21, ans_no_idx21[1:] + [None])]
- all_item_ans.extend(rest_item_split)
- ans_no = ans_no3
- else:
- print('答案第3种切分方案:存在一行多个答案,且每个答案题号前必须有空格或顶格')
- rest_item_split = [del_no(("\n" + anss_str)[i:j]) for i, j in
- zip(ans_no_idx1, ans_no_idx1[1:] + [None])]
- all_item_ans.extend(rest_item_split)
- ans_no = ans_no2
- else:
- print('答案第2种切分方案:没有一行多个答案的情况!')
- rest_item_split = [del_no(k) for k in rest_item_split]
- all_item_ans.extend(rest_item_split)
- ans_no = ans_no1
- return all_item_ans, ans_no
- def get_ans_match(item_res, all_ans, ans_no, *group):
- """
- 根据切分后的答案及其题号,与前面试题进行匹配更新,all_ans和ans_no的个数应该是相同的
- :param item_res:
- :param all_ans:
- :param ans_no:
- :return:
- """
- for k, one_ans in enumerate(all_ans):
- temp_id = "no"
- # 从试题的res寻找与当前答案题号相同的题目的位置
- temp_id_list = [i for i, v in enumerate(item_res) if k<len(ans_no) and v["item_id"] == ans_no[k]]
- if len(temp_id_list) == 1:
- temp_id = temp_id_list[0]
- elif len(temp_id_list) > 1:
- for j in temp_id_list:
- if "key" not in item_res[j].keys():
- temp_id = j
- if temp_id != 'no': # 找到题目和答案相同的题目的序号时,没找到就先不要答案了
- res_con = item_res[temp_id]['stem']
- if group==((),) or not group: # 这里group参数是双层嵌套不定参数,if not group[0]
- if k<= len(item_res)-1:
- simp_res = only_parse_split(one_ans, item_res[temp_id]["type"], res_con)
- item_res[temp_id].update(simp_res)
- else:
- item_res[temp_id].update({'key': "", 'parse': ""})
- else:
- if group == 'group_ans':
- item_res[temp_id]['key'] = one_ans
- item_res[temp_id]['parse'] = ""
- if group == 'group_parse':
- item_res[temp_id]['parse'] = one_ans
- if not item_res[temp_id]['key']:
- item_res[temp_id]['key'] = '见解析'
- return item_res
- def anss_split_contain_slave(subject, ans_str):
- """
- 针对地理中,一个材料多个小题的题目(含选择题),答案不连续且都是从1开始编号的情况按【答案】拆分
- :param subject:
- :return:
- """
- if subject == "地理":
- print("地理学科")
- anss_split_by_key = re.split("\n\s*\d+\s*[、..、::]\s*【答案】|^\s*\d+\s*[、..、::]\s*【答案】",
- ans_str)
- if len(anss_split_by_key) > 1 and (not anss_split_by_key[0] or ("【答案】" not in anss_split_by_key[0] and
- "【解析】" not in anss_split_by_key[0])):
- anss_split_by_key = anss_split_by_key[1:]
- for one_ans in anss_split_by_key:
- parses = one_ans.split("【解析】",maxsplit=1)
- temp_ans_no1, ans_no_idx1 = get_many_ans_no(one_ans, 1) # 初步获取
- temp_ans_no1, ans_no_idx1 = get_right_no((ans_no_idx1, temp_ans_no1), 1) # 筛选
- if __name__ == '__main__':
- # one_item_ans = """
- # (12分)
- # (1)泥泞路面上行驶时,汽车受到的阻力为8000N;
- # (2)速度为10m/s时,汽车的加速度-2m/s<sup>2</sup>;
- # (3)汽车在AB段上的运动时间为30.625s.
- # """
- # res_con = """
- # (12分如图所示,一质量为2×10<sup>3</sup>kg的小汽车从倾斜路面上以20m/s的速度经A点驶入泥泞的水平路面,行驶200m路程后到达B点,速度降为5m/s,此后速度保持恒定,已知整个过程中汽车发动机的输出功率恒为40kW.求:
- # (1)泥泞路面上行驶时,汽车受到的阻力;
- # (2)速度为10m/s时,汽车的加速度;
- # (3)汽车在AB段上的运动时间.
- # """
- # rr=only_parse_split(one_item_ans, "计算题", res_con)
- # print(rr)
- a=get_array_ans('1.B 2. C 3. D 4. B 5. B 6. C 7. B 8.A 9. AD 10. ACD 11. BC 12. CD', [], 1)
- print(a)
|