washutil.py 53 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027
  1. #!/usr/bin/env/python
  2. # -*- coding:utf-8 -*-
  3. # 本文件包含以下函数
  4. # table_label_cleal:去掉表格中的换行符
  5. # html_cleal :html文件清洗
  6. # wash_after: 处理最终结果多余的换行符
  7. import re
  8. import shutil
  9. # from operator import itemgetter
  10. # from itertools import groupby
  11. # from PIL import Image
  12. import base64, os, random
  13. import time
  14. import hashlib
  15. from pprint import pprint
  16. # from bs4 import BeautifulSoup
  17. # UPLOAD_FOLDER = config.UPLOAD_FOLDER
  18. import configs
  19. from structure.stems_to_groups import parse_split2group, suojin
  20. from utils.equation_extract import get_equation_instr, get_simpstr2eqn
  21. from utils.field_eq2latex import get_latex
  22. from utils.html_again_parse import css_label_wash
  23. from structure import stems_to_groups
  24. def table_label_cleal(con):
  25. """
  26. 去掉表格中的【换行符】
  27. """
  28. # print(con)
  29. # print('------------------------------------------')
  30. con = re.sub(r"<br\s*/?>", "\n", con)
  31. con = re.sub(r"\n(\n|\t)+", "\n", con)
  32. count = 1
  33. while re.search(r"</?[a-z]+>\n(</?[a-z]+>|<td\s+\n*[a-z=\"\d]+>)", con, re.S) and count <= 10:
  34. con = re.sub("(</?t[dr]>|</?table>|</?tbody>|</?div>)\n(</?t[dr]>|</div>|</?table>|</?tbody>|<p>)",
  35. r"\1\2", con, flags=re.S)
  36. con = re.sub(r'(</?t[rd]>)\n(<td\s.+?>)', r'\1\2', con, flags=re.S)
  37. count += 1
  38. # if re.search(r"<table>(.|\n)+?</table>", con, re.S|re.M):
  39. # aa = re.search(r"(<table>(.|\n)+?</table>)", con, re.S|re.M)
  40. # con = con.replace(aa.group(1),aa.group(1).replace("\n",""))
  41. # 将空表格的情况去掉
  42. con = re.sub(r'<table>[\s\n\t]*?<tbody>[\s\n\t]*?(<tr>[\s\n\t]*?<td[^<>]*?>[\s\n\t]*?<p>[\s\n\t]*?</p>'
  43. r'[\s\n\t]*?</td>[\s\n\t]*?</tr>[\s\n\t]*?)+</tbody>[\s\n\t]*?</table>[\s\n\t]*?<p>', "", con,
  44. flags=re.S)
  45. con = re.sub(r'(</table><p>)\s*([((]\s*\d\s*[))])', r'\1\n\2', con)
  46. return con
  47. def base642img(html_data, wordid):
  48. """
  49. 【基于mathjax渲染输出是css-html格式】
  50. 将base64编码的图片保存到本地
  51. :return:
  52. """
  53. # 二进制图片进行转化, 按“word_id”建立文件夹
  54. # time_str = datetime.datetime.strftime(datetime.datetime.now(), '%Y_%m_%d')
  55. # file_path = configs.IMG_FOLDER + '/' + str(self.wordid)
  56. # if not os.path.exists(file_path):
  57. # os.makedirs(file_path)
  58. # else:
  59. # 思路1:删除图片,重建文件夹,【所有的新图片都是以base64格式传过来的】
  60. # shutil.rmtree(file_path)
  61. # os.makedirs(file_path)
  62. # 思路2:每一次再解析都将base64图片保存到本地再以路径形式返回
  63. # st = len(os.listdir(file_path)) # 不要以序号索引的形式命名
  64. # 统计所有base64编码
  65. all_base64_image = re.findall(r'(<img ([a-z]+="[^"]*?" )?src="(data:image[^>"]+?)"(.*?)\s*/?>)', str(html_data), flags=re.S)
  66. if all_base64_image:
  67. file_path = configs.IMG_FOLDER + '/' + str(wordid)
  68. if not os.path.exists(file_path):
  69. os.makedirs(file_path)
  70. # 新图片命名1、时间戳+随机数;2、md5值命名
  71. # name_list = random.sample(range(100000, 999999), len(all_base64_image))
  72. for n, img in enumerate(all_base64_image):
  73. img1 = img[2].split(",", maxsplit=1)
  74. img_type_info = re.search("data:image/(.+?);base64", img1[0])
  75. img_type = img_type_info.group(1) if img_type_info else "" # 图片格式
  76. # 可能还有alt和style的属性,暂时先不要
  77. w_info = re.search('( width="\d+")', img[3])
  78. h_info = re.search('( height="\d+")', img[3])
  79. img_data = base64.b64decode(str(img1[-1]))
  80. if img_type:
  81. # save_path = os.path.join(configs.new_img_ip, get_md5(n)+"."+img_tape)
  82. pmd5 = hashlib.md5(img_data)
  83. # img_name = "new_image" + str(int(time.time())) + str(name_list[n]) + "." + img_type # 时间戳+随机数
  84. img_name = "new_image" + pmd5.hexdigest() + "." + img_type
  85. save_path = os.path.join(file_path, img_name)
  86. with open(save_path, 'wb') as f:
  87. f.write(img_data)
  88. flag_behind = '" />'
  89. if w_info and h_info:
  90. flag_behind = '"' + w_info.group(1) + h_info.group(1) + ' />'
  91. temp_img = '<img src="' + configs.new_img_ip + '/' + str(wordid) + '/' + img_name + flag_behind
  92. html_data = html_data.replace(img[0], temp_img)
  93. return html_data
  94. class HtmlWash:
  95. """
  96. html文本清洗
  97. 批量再解析中,新增图片信息替换的文本返回作为ocr保存文本,
  98. 继续往下清洗的文本,则进入结构化解析逻辑中
  99. """
  100. def __init__(self, html, wordid, subject, is_reparse=0):
  101. """
  102. html文本清洗
  103. 批量再解析中,新增图片信息替换的文本返回作为ocr保存文本,
  104. 继续往下清洗的文本,则进入结构化解析逻辑中
  105. """
  106. # super().__init__(html, wordid, is_reparse, must_latex)
  107. self.html = html
  108. self.wordid = wordid
  109. self.is_reparse = is_reparse
  110. self.subject = subject
  111. self.sub_list = ["</?div>", "</?b>", "</?caption>", "</?center>", "</?cite>", "</?code>", "</?colgroup>",
  112. "</?menu>", "</?dd>", "</?dir>", "</?li>", "</?article>", "</?header>", "</?ruby>",
  113. "</?summary>", "</?details>", "</?strike>", "</?small>", "</?select>",
  114. "</?section>", "</?script>", "</?[su]>", "</?var>", "</?ul>", "</?tt>", "</?title>",
  115. "</?thead>",
  116. "</?tfoot>", "<hr />", "<hr>", ""]
  117. self.sub_dd = {'&times;': '×',
  118. '&divide;': '÷',
  119. '&deg;': '°',
  120. '&middot;': '·',
  121. '&plusmn;': '±',
  122. '&ordm;': 'º',
  123. '&sup1;': '¹',
  124. '&sup2;': '²',
  125. '&sup3;': '³',
  126. '&frac12;': '1/2',
  127. '&frac14;': '¼',
  128. '&frac34;': '¾',
  129. '&yen;': '¥',
  130. 'm&sup3;': 'm³',
  131. # '&lt;': '<',
  132. '&pound;': '£',
  133. # '∠&lt;': '&lt;',
  134. '&gt;': '>',
  135. "A": "A",
  136. "А": "A",
  137. "Α": "A",
  138. "B": "B",
  139. "В": "B",
  140. "в": "B",
  141. "Β": "B",
  142. "C": "C",
  143. "С": "C",
  144. "c": "c",
  145. "с": "c",
  146. "D": "D",
  147. "Ε": "E",
  148. "E": "E",
  149. "F": "F",
  150. "G": "G",
  151. "g": "g",
  152. "m": "m",
  153. "N": "N",
  154. "s": "s",
  155. "t": "t",
  156. "/": "/",
  157. "=": "=",
  158. "-": "-",
  159. "2": "2", "3": "3", "4": "4", "5": "5", "6": "6",
  160. "7": "7", "8": "8", "9": "9", "1": "1", "0": "0",
  161. '&nbsp;&nbsp;': ' ',
  162. '&nbsp;': ' ',
  163. "〖": '【',
  164. "〗": '】',
  165. "題": '题',
  166. "单项选择": '单选',
  167. "多项选择": '多选',
  168. "不定项选择": '选择',
  169. "双项选择": '多选',
  170. "实验与探究题": '实验',
  171. }
  172. def new_pic_sub(self):
  173. """
  174. 针对base64图片先保存到本地,入库时再换成腾讯云线上地址
  175. # 第一版:再解析中,将二进制图片进行转化,图片怎么保存比较好,先再“天数”建立文件夹
  176. 第一版:再解析中,根据“word_id”建立文件夹
  177. :return:
  178. """
  179. if self.is_reparse:
  180. # css 标签清洗
  181. self.html = css_label_wash(self.html)
  182. # print(self.html)
  183. # 保存base64编码的图片
  184. self.html = base642img(self.html, self.wordid)
  185. self.new_html = self.html
  186. self.new_html = table_label_cleal(self.new_html)
  187. self.new_html = self.new_html.replace("\n", "<br/>")
  188. def html_cleal(self):
  189. # =======清洗mathjax标签========
  190. if "MathJax" in self.html: # 再解析中存在mathjax公式渲染的标签
  191. all_mathjax = re.findall('(<span class="MathJax_Preview".*?</script>(</span>)*)', self.html)
  192. for jax in all_mathjax:
  193. latex = re.findall('<script .+?">(((?!(</)).)*?)</script>(</span>)*', jax[0])
  194. if latex:
  195. latex = "${}$".format(latex[0][0])
  196. self.html = self.html.replace(jax[0], latex)
  197. else:
  198. self.html = self.html.replace(jax[0], "")
  199. # ======再解析中的css清洗及新图片处理=====
  200. self.new_pic_sub()
  201. # =====特殊符号处理=====
  202. html2txt = re.sub(r"|".join(self.sub_list), "", str(self.html)) # ("", " ") #2020/4/7
  203. html2txt = re.sub("|".join(self.sub_dd.keys()), lambda x: self.sub_dd[x.group()], html2txt) # 2020/4/1,4/7,4/20
  204. html2txt = re.sub("[不非]定[向项]选择", "不定选择", html2txt)
  205. html2txt = html2txt.replace(r"\\[{\\text{V}}V\]", "Ⓥ").replace(r"\\[{\\text{A}}A\]", "Ⓐ") \
  206. .replace(r"\\[{\\text{W}}W\]", "Ⓦ").replace(r"\\[{\\text{X}}X\]", "Ⓧ").replace(r"\\[{\\text{G}}G\]", "Ⓖ") \
  207. .replace("\uf067", "γ").replace('', "γ").replace('\uf020', "").replace("\u3000", " ")\
  208. .replace("\u2003", " ").replace("\x7f", " ").replace("\xa0", "")
  209. html2txt = re.sub(r"(<p>\s*)【例题(\d+)】", r"\1\2、", html2txt)
  210. html2txt = re.sub(r"\\\(|\\\)", "$", html2txt)
  211. # 把格式标签单独拆分为一行,再在题目切分为小题完了之后再组起来!!!!!
  212. html2txt = re.sub(r'(<p style="text-(indent|align):.*?">)', r"\1</p><p>", html2txt)
  213. # 域公式的转化处理;<sub>\<sup>可以在前端显示,不需要用latex渲染
  214. try:
  215. html2txt, newhml = get_latex(html2txt, self.is_reparse, self.wordid)
  216. if newhml: # 存在域公式转图片时,需要将原文本的域公式也转为图片信息
  217. self.new_html = newhml
  218. html2txt = html2txt.replace("【omml-latex】", "")
  219. except:
  220. html2txt = html2txt.replace("【omml-latex】", "")
  221. # 字符串公式的处理:如Fe<sub>2</sub>O<sub>3</sub>, 在结构化之后处理比较好
  222. # <br/>处理
  223. html2txt = re.sub(r"<br\s*/?>", "\n", html2txt)
  224. # =====题型行的统一处理=====
  225. # ---->>>>>题型行可能放在表格中
  226. if len(re.findall("</table>", html2txt)) >= 8: # 这个限制还不太严谨
  227. for tt in re.finditer('<tr>(((?!(</?tr>)).)*)</tr>', html2txt, re.S):
  228. tt_list = re.split(r'^\s*<td[^<>]*?>|</p></td>|</td>[\n\s]*?<td[^<>]*?>'
  229. r'|</td>\s*\n|</td>\s*$|\n\s*<td[^<>]*?>|<td[^<>]*?><p>',
  230. tt.group(1).strip()) # </td>\s*[$\n]这样无效
  231. tt_list = [col for col in tt_list if col.strip()]
  232. if " ".join(tt_list).replace(" ", "") in ['得分评卷人', '评卷人得分']:
  233. html2txt = html2txt.replace(tt.group(0), "")
  234. else:
  235. pass
  236. # html2txt = html2txt.replace(tt.group(0), "<p>" + " ".join(tt_list) + "</p>")
  237. # html2txt = re.sub(r"</?tbody>|</?table>|</?div>", "", html2txt)
  238. # ---->>>>>end
  239. html2txt = re.sub(r"(</table>)\s*([一二三四五六七八九十]\s*[、..、::]?.{2,6}题)", r"\1</p>\2", html2txt)
  240. html2txt = re.sub(r'([一二三四五六七八九十])\s*[、..、,,::]\s*(论述|填空|探究)题?[与和、、,,\s]*?(计算题|实验题)', r"\1、\3", html2txt)
  241. html2txt = re.sub(r'<td[^<>]*?><p>(([一二三四五六七八九十])\s*[、..、,,::]\s*(.{2,4}题)\s*</p>)</td>[^p]*?<p>', r"\1",
  242. str(html2txt), flags=re.S)
  243. html2txt = re.sub(r'<td[^<>]*?>\s*(([一二三四五六七八九十])\s*[、..、,,::]\s*(.{2,4}题)\s*)</td>[\n\s]*?</tr>', r"\1",
  244. str(html2txt), flags=re.S)
  245. html2txt = re.sub(r"<p>\s*([一二三四五六七八九十])\s*[、..、,,::]?\s*(计算|[解简]答|实验|作图)题?[与和、、,,\s]*?(计算|[解简]答|实验|作图)",
  246. r"<p>\1、\2题", html2txt)
  247. html2txt = re.sub(r'<p>\s*[((]\s*[一二三四五六]\s*[))]\s*必考题\s*(.?|.+?分\s*[.。.]?)\s*</p>', "", html2txt)
  248. html2txt = re.sub(r'<p>\s*[((]\s*[一二三四五六]\s*[))]\s*选考题\s*.?\s*.{,4}(?<!\d)(\d+分)\s*[,,。].{,50}</p>',
  249. r"<p>【选做题】:'\1'</p>", html2txt)
  250. html2txt = re.sub(r'<p>\s*[((]\s*[一二三四五六]\s*[))]\s*选考题\s*(.?|.+?分\s*[.。.]?)\s*</p>', "<p>【选做题】</p>", html2txt)
  251. html2txt = re.sub(r'<p>\s*([一二三四五六七八九十])\s*[、..、,,::]?\s*(单项?选择?|非?选择|多项?选择?|不定选择|填空|计算|[解简]答|实验|作图)题?\s*</p>',
  252. r"<p>\1、\2题</p>", html2txt)
  253. html2txt = re.sub(r'([一二三四五六七八九十])\s*[、..、,,::]?\s*(单选|单项选择|选择|不定选择|多选|多项选择|填空|计算|[解简]答|实验|作图)\s*(?!题)'
  254. r'([((]\s*本题|.*?\d分)', r"\1" + "、" + r'\2' + "题" + r"\3", html2txt)
  255. html2txt = re.sub(r'([一二三四五六])\s*[、..、,,::]?\s*(单选|单项选择|非?选择|不定选择|多选|多项选择|填空|计算|[解简]答|实验|作图)题',
  256. r"\1" + "、" + r'\2' + "题", html2txt)
  257. html2txt = re.sub(r'([一二三四五六七八九十])\s*[、..、,,::]?\s*[((]\s*本大题(.*?选项中)', r"\1" + "、" + "选择题", html2txt) # + r"\2"
  258. html2txt = re.sub(r'<p>\s*([一二三四五六七八九十])\s*[、..、,,]?\s*[((本大题]*?(.*?选项中)', r"\1" + "、" + "选择题", html2txt)
  259. if self.subject != "语文":
  260. html2txt = re.sub(r'([一二三四五六七八九十])\s*[、..、,,::]?\s*([((]\s*(每小题|本大?题)((?!(选项)).)+?[))]|综合题)',
  261. r"\1" + "、" + "解答题", html2txt)
  262. else:
  263. html2txt = re.sub(r'([一二三四五六七八九十])\s*[、..、,,::]?\s*([((]\s*(每小题|本大?题)((?!(选项)).)+?[))]|综合题)',
  264. r"\1" + "、" + "综合题", html2txt)
  265. html2txt = re.sub(r'(?<!<p>)\s*([一二三四五六七八九十]\s*[、..、,,::]?\s*(单项?选择?|选择|不定选择|多项?选择?|填空|计算|[解简]答|实验|作图)题)',
  266. r'</p>\n<p>\1', html2txt)
  267. # html2txt = re.sub(r'<p>\s*第[Ⅰ1I]卷\s*</p>\n?<p>\s*本卷共\d{1,2}个?小?题.*?四个选项.*?\n?<p>\s*(\d\s*[、..、])'
  268. # r'|<p>第[Ⅰ1I]卷\s*[((]选择题[))]</p>\n?<p>本卷共\d{1,2}个?小?题.*?\n?<p>\s*(\d\s*[、..、])',
  269. # r"<p>一、选择题</p>\n<p>\1\2", html2txt)
  270. # html2txt = re.sub(r'<p>\s*[^一二三四五六七八九十]{,3}\s*[、..、]\s*(选择|不定选择|单选|多选|计算|[解简]答|实验|作图)题', r"<p>一、\1题", html2txt)
  271. # =====答案解析关键字的统一处理=====
  272. html2txt = re.sub(r'【\s*(<img src=((?!/>).)+?/>\s*)*?([解答])\s*(<img src=((?!/>).)+?/>\s*)*?([析案])\s*'
  273. r'(<img src=((?!/>).)+?/>\s*)*?】', r"【\3\6】", str(html2txt)) # 2022/4/28
  274. html2txt = re.sub(r'<p>\s*(解\s*[::])', r"<p>【解答】", str(html2txt))
  275. html2txt = re.sub(r'(<p>|<br\s*/>|\n)\s*(参考译文\s*[::])', r"\1【参考译文】", str(html2txt))
  276. html2txt = re.sub(r'【[^【】]*?(答案|[解分][析答]|详解|点[评睛])[^【】]*?】', r"【\1】", str(html2txt))
  277. html2txt = re.sub(r'(\n\s*|\s{2,})(答案|解析|解答|详解|点评|点睛|考点|专题)\s*[::]', r"\1【\2】", str(html2txt))
  278. html2txt = re.sub(r'(\n|^|<p>)\s*(([1-9]|[1-4][0-9])\s*[..、、])?\s*\[\s*(答案|解析|解答|详解|点评|点睛|考点|专题)\s*\]',
  279. r"\1\2【\4】", str(html2txt))
  280. html2txt = re.sub(r'(\n|^)\s*(分析)\s*[::]', r"【\2】", str(html2txt))
  281. if "【解析】" not in html2txt and "【解答】" in html2txt and "【分析】" not in html2txt:
  282. html2txt = re.sub(r'【解答】', "【解析】", str(html2txt))
  283. # =====其他关键字的处理=====
  284. html2txt = re.sub(r'<p>\s*(类型|知识点|考查角度|拔尖角度)[一二三四五六七八九十\d+][^p]*?</p>', "", str(html2txt))
  285. html2txt = re.sub(r'<p>\s*(选修[\d-]*?[::].{2,15})\s*</p>', r"<p>【章节】\1</p>", html2txt)
  286. html2txt = re.sub(r'<p>\s*([一二三四五六]\s*[、..、]?)?\s*(\[.{2}-*?选修[\d-]*?.*?\])\s*([((]\d+分[))])?\s*</p>',
  287. r"<p>【章节】\2</p>", html2txt)
  288. html2txt = re.sub(r'<p>\s*(基础|中档|综合)题[^p题]*?</p>|<p>\s*【(考点|专题)】[^p]*?</p>', "", str(html2txt))
  289. html2txt = re.sub(r'<p>\s*(基础训练|提升训练|探究培优)</p>', "", str(html2txt))
  290. html2txt = re.sub(r'<p>注意事项[::]\s*</p>(\n+\s*<p>\s*\d\s*[、..、][^/]+?</p>)+', "", html2txt, flags=re.S)
  291. html2txt = re.sub(r'<p>注意事项[::]\s*\d\s*[、..、][^/]+?</p>(\n+\s*<p>\s*\d\s*[、..、][^/]+?</p>)+', "", html2txt,
  292. flags=re.S)
  293. html2txt = re.sub(r'[((]\s*([A-Z\dⅠⅡⅢⅣⅤ]+|IV)\s*[))]', r"(\1)".replace(" ", "").replace("(IV)", "Ⅳ"), html2txt)
  294. html2txt = re.sub(r'[((](\s*\d\s*\d?\s*分?\s*)[))]', "(" + r'\1'.replace(" ", "") + ")", html2txt)
  295. html2txt = re.sub(r'\[来源:.*?\]', "", html2txt)
  296. html2txt = re.sub('<p>欢迎访问.*?</p>', '', html2txt)
  297. html2txt = re.sub('w\s*w\s*w\..*?(\.\s*c\s*o\s*m|\.cn)+|(?<!["“=])http:.*?\.(com|cn|org)', "",
  298. html2txt) # ww w.gkstk.com
  299. # html2txt = re.sub(r'<(table|td|tr) ([a-z]+="\d+")>', r'<\1>', html2txt)
  300. html2txt = re.sub(r'<table ([a-z]+="\d+")>', r'<table>', html2txt)
  301. html2txt = re.sub(r'<p>\s*第\s*[二三四ⅡⅢⅣ]\s*(卷|部分)\s*([((].*?[))]|非?选择题.{,8})?\s*</p>', "<p>【非选择题】</p>", html2txt)
  302. # == == =对可能的题型行的处理 == ==
  303. html2txt = re.sub("<p>【非选择题】</p>((\s|\n|<p>|</p>)*\d{1,2}\s*[..、、].+?)", r"<p>二、解答题</p>\1", html2txt)\
  304. .replace("【非选择题】", "")
  305. # =====选项的处理=====
  306. html2txt = re.sub(r'(<p>\s*([1-9]|[1-9][0-9])\s*[..、、].+?[((]\s*[))])\s*(A\s*[..、、][^/]*?</p>)',
  307. r"\1</p>\n<p>\3", str(html2txt))
  308. # =====题号的处理=====
  309. html2txt = re.sub(r'([ED]\s*[、..、].*?(\s|</su[pb]>\s*))(([1-9]|[1-9][0-9])\s*[、..、])',
  310. r"\1</p>\n<p>\3", html2txt)
  311. html2txt = re.sub(r'((</?p>|\n)\s*(<img src=.*?"\s*/?>\s*)?([1-9]|[1-9][0-9]))\s*'
  312. r'([((]\s*(\d{1,2}[.\s\d]*?分|.{2,3}题?)\s*[))]|解析?\s*[::]|【解析】)', r"</p>\1、\5", html2txt)
  313. html2txt = re.sub(r"<p>\s*([1-9]|[1-9][0-9])\s*([((]20\d{2}\s*[\u4e00-\u9fa5、、]{2,9}[))])", r"<p>\1、\2",
  314. html2txt)
  315. html2txt = re.sub(r"<p>\s*([1-9]|[1-9][0-9])\s*(【(解析?|答案?)】|(解析?|答案?)\s*[::]|\[(答案|解析)\])", r"<p>\1、\2",
  316. html2txt)
  317. html2txt = re.sub(r"<p>\s*([1-9]|[1-9][0-9])\s*([((]\s*\d+\s*分?\s*[))])?(【(解析?|答案?)】|(解析?|答案?)\s*[::]"
  318. r"|\[(答案|解析)\])", r"<p>\1、\2\3", html2txt)
  319. html2txt = re.sub(r"(</?p>|\n)\s*(<img src=((?!/>).)+?/>)\s*([1-9]|[1-9][0-9])\s*"
  320. r"([((]20\d{2}\s*[\u4e00-\u9fa5、、]{2,9}[))])", r"<p>\2</p>" + "\n" + r"<p>\4、\5", html2txt) # 【susp_img】
  321. html2txt = re.sub(r'(</?p>|\n)((\s*<su[bp]>\s*)?<img src=.*? height="[\d.]+p[tx]"\s*/?>(\s*</su[bp]>)?\s*)'
  322. r'(([1-9]|[1-9][0-9])\s*[、..、])', r"</p>\2</p>" + "\n" + r"\5", html2txt)
  323. html2txt = re.sub(r"(<p>((?!<p>).)+?(\s|[/\"]>))(([1-9]|[1-9][0-9])\s*[、..、].{,20}本[大小]?题\d+分)",
  324. r"\1</p>" + "\n<p>" + r"\4", html2txt)
  325. html2txt = re.sub(r"</?p>((\s*<su[bp]>\s*)?<img src=.*?/>(\s*</su[bp]>)?((\s*<su[bp]>\s*)?"
  326. r"<img src=((?!/>).)+?/>(\s*</su[bp]>)?)*?\s*)\s*(([1-9]|[1-9][0-9])\s*[、..、])",
  327. r"</p>\1</p>" + "\n<p>" + r"\8", html2txt, flags=re.S)
  328. html2txt = re.sub(r'(<p>\s*[一二三四五六七八九十].*?题\s*\(.+?分.*?\))\s*(([1-9]|[1-9][0-9])\s*[、..、].*?)</p>',
  329. r"\1</p>\n<p>\2</p>", html2txt)
  330. html2txt = re.sub(r'(<p>\s*[一二三四五六七八九十].*?题\s*\(.+?分.*?\))\s*(([1-9]|[1-9][0-9])\s*[、..、].*?)</p>',
  331. r"\1</p>\n<p>\2</p>", html2txt)
  332. html2txt = re.sub(r'(<p>.*?[..]{6,}\s*\d+分)\s*(([1-9]|[1-9][0-9])\s*[、..、].*?)</p>', r"\1</p>\n<p>\2</p>", html2txt)
  333. html2txt = re.sub(r'([1-9]|[1-9][0-9])\s*([((]\s*\d{1,2}[.\s\d]*?分\s*[))])\s*[、..、]', r"\1" + "、" + r"\2", html2txt)
  334. # =====图片的处理=====
  335. # 1>>根据图片宽高的异常值判断删除隐藏图片
  336. def sub1(ss):
  337. if float(ss.group(1)) <= 3 and float(ss.group(2)) <= 3:
  338. return ""
  339. else:
  340. return ss.group(0)
  341. html2txt = re.sub(r'<img src=.*? width="([\d.]+)p[xt]" height="([\d.]+)p[xt]"\s*/?>', sub1, html2txt)
  342. # 2>>将图片中带有的汉字去掉
  343. html2txt = re.sub(r'(<img src=.*?) alt=".+?"', r"\1", html2txt)
  344. html2txt = re.sub(r'(<img src=(?!\sstyle=)+?(?<!\\)\")>', r"\1 />", html2txt) # 将">换为" />
  345. # 3>>建立图片id字典,对原图片信息第一次替换
  346. html2txt = re.sub(r'( src=".*?files)\\image', r"\1/image", html2txt)
  347. all_image = re.findall(r'<img src=".*?image[\da-z]+\..*?[/\"]>', html2txt)
  348. src2subs = {}
  349. subs2src = {}
  350. for src in all_image:
  351. # 校本题库上传的图片名称是随机数,故设置映射
  352. # kk = re.search('(<img src=".*?image\d+\.(png|gif|jpg|jpeg))', src)
  353. # new_src = src.replace(kk.group(1), self.img_url[kk.group(1)]) if type(self.img_url) == dict and kk else src
  354. # 图片信息简化替换
  355. new_src = re.sub(r'( data-latex)="\s*\\\[(.*?)\\\]\s*"', r'\1="$\2$"', src)
  356. new_src = re.sub(r'( data-latex="\$[^"]+?\$")',
  357. lambda x: x.group(1).replace("<", " \lt ").replace(" ", " "), new_src)
  358. latex_info = re.search(r'<img src=".*?/(new_)?image([\da-z]+)\..*?(data-latex=".*?")', src)
  359. mathpix = " " + latex_info.group(3).replace("\n", "").strip().replace(" ", " ") if latex_info else ""
  360. if mathpix and len(mathpix) > 20:
  361. mathpix = ""
  362. w_h_info = re.search(r'<img src=".*?/(new_)?image([\da-z]+)\..*?width="([\d.]+)[pxt]*?"\s*height="([\d.]+)[pxt]*?"', src)
  363. w_h = " w_h=" + w_h_info.group(3).split('.')[0] + "*" + w_h_info.group(4).split('.')[0] \
  364. if w_h_info and not mathpix else "" # w_h 和 mathpix只存在一个
  365. image_id = re.search(r'<img src=".*?/(new_)?image([\da-z]+)\.', src).group(2)
  366. src2subs[src] = '<imgsrc' + image_id + w_h + mathpix + "/>"
  367. subs2src['<imgsrc' + image_id + w_h + mathpix + "/>"] = new_src
  368. for k, v in src2subs.items():
  369. html2txt = html2txt.replace(k, v)
  370. # ------------------------------------------------------------------------
  371. # ========html 转 list=========
  372. html2txt = re.sub(r'(</?div>|</table>|</?body>)(\n\s*)*?<p>', r"\1</p>" + "\n<p>", html2txt, flags=re.S)
  373. # >>>>>> <table>先替换后再切割
  374. # 不能简单按 \n 切割,表格里面也可能有换行,应该先替换后再切割
  375. subs2table = {}
  376. all_table = re.findall(r'<table>.*?</table>', html2txt, flags=re.S)
  377. for k, v in enumerate(all_table):
  378. subs2table["<t{}b>".format(str(k))] = v
  379. html2txt = html2txt.replace(v, "<t{}b>".format(k))
  380. # <造成的css标签冲突处理 2021-10-13
  381. def sub2(ss):
  382. if re.search(r'^(img|/?h[123456]|/?su[bp]>|t\d+b>|br\s*/?>'
  383. r'|/?(p|span|font|article|ul|ol|div|strong|em|table|t?body|html|head|t[drh])(\s*|\s+style=.*?")>'
  384. r'|/?[a-z]+ (style|rowspan|colspan|class)=.*?">)', ss.group(1)) is None:
  385. r1 = "&lt;{}".format(ss.group(1))
  386. r1 = re.sub(r"&lt;(span (class|style)=)", r"<\1", r1)
  387. r1 = re.sub(r"&lt;(p (class|style)=)", r"<\1", r1)
  388. return r1
  389. else:
  390. return "<{}".format(ss.group(1)).replace("</body>", "").replace("</html>", "")
  391. html2txt = re.sub("<([^<]{1,30})", sub2, html2txt)
  392. # >>>>>> html 切割
  393. con_list = sum([re.split('<p>|<h[12345]>', i) if len(re.findall("<p>|<h[12345]>", i)) > 1
  394. else [i] for i in re.split(r"\n+|</p>(?!</td>)|</h[12345]>", html2txt)], []) # html2txt)[:-1]
  395. con_list = [re.sub(r"^\n*\s*(<p>|<h[12345]>)+", "", ii) for ii in con_list]
  396. # pprint(con_list)
  397. # >>>>>> <table> 替换回去
  398. if subs2table:
  399. con_list = [re.sub(r"|".join(subs2table.keys()), lambda x: subs2table[x.group()], ii) for ii in con_list]
  400. # 剩余个别标签处理
  401. con_list = [re.sub(r"^<([a-z]+)>[\s\t\n]*</\1>$", "", i.strip()) for i in con_list] # 2020/4/7,14
  402. con_list = [re.sub(r"^(<table>|</td>|<td[^<>]*?>|</?tr>)+?(.|\n)+?([一二三四五六七八九十])\s*[、..、]\s*(.{2,4}题)(.|\n)+?</table>",
  403. r"\3、\4", i.strip())
  404. for i in con_list]
  405. # 把最后可能还存在的</?p>或考号信息去掉
  406. con_list = [re.sub("</?p>|[…O•.\s]*?密[…O•.\s]*?封[….O•\s]*?装?[…O•.\s]*?订?[….O•\s]*?线?[….O•\s]*?$"
  407. "|((学校|班级|姓名|座位号|准考号|[学考]号)[\s::_]*?){2,}$", "", i.strip()) for i in con_list]
  408. # =====答案行格式处理====
  409. temp_list = [re.split(r"^((\s*<imgsrc((?!/>).)*?/>\s*)+)", v.strip(), maxsplit=1)[1::3]
  410. if re.match(r'(\s*<imgsrc((?!/>).)*?/>\s*)+?(参考|考试|试[题卷]|物理|理综|数学|化学|生物)'
  411. r'(答案|解析|答案[及与和]评分(标准|意见|细则))\s*$'
  412. r'|(\s*<imgsrc((?!/>).)*?/>\s*)+?评分标准'
  413. r'|(\s*<imgsrc((?!/>).)*?/>\s*)+?(参考|考试|试[题卷])'
  414. r'(答案|解析|答案[及与和]评分(标准|意见|细则))\s*(物理|理综|数学|化学|生物)?\s*$',
  415. re.sub(r"[上下]?学[年期]|[\d—【】..、、::(())年\s]|[中大]学|模拟|[中高]考|年级|[学期][末中]|[高初][一二三]", "",
  416. v.strip())) else [v] for v in con_list]
  417. con_list = sum(temp_list, [])
  418. # =====对可能的题号的处理==== 如2、3、4、5、 加了【fei】 # 重新修改!!!!!!!!!!
  419. con_list = [re.sub(r"^\s*([1-9][0-9]?\s*[..、、])", r"【fei】\1", i.strip())
  420. if (len(re.findall(r"(^|\s*[..、、])\s*[1-9][0-9]?\s*[..、、]", i)) >= 3
  421. and len(re.sub(r"[\d..、、\s]", "", i)) < 2) else i for i in con_list]
  422. # =====头尾清除没用的信息=====
  423. if con_list and re.search(r"[\u4e00-\u9fa5]|<img | style=\"text-(indent|align)"
  424. r"| style=\"text-decoration| class=\"dots\"|<strong>|<em>", con_list[0]) is None:
  425. con_list = con_list[1:]
  426. while con_list and re.search(r"声明[::].*?著作权属.*?所有|(邮箱|用户|日期|QQ)\s*[::].+?", con_list[-1]):
  427. con_list = con_list[:-1]
  428. return con_list, subs2src, self.new_html
  429. def del_no(item, item_no_type=1):
  430. """去开头的题号"""
  431. if item_no_type == 2:
  432. item = re.sub(r'^\n*\s*[((]\s*([1-9]|[1-9][0-9])\s*[))]\s*[..、、::]?', "", item)
  433. return item
  434. item = re.sub(r'^\n*\s*([1-9]|[1-9][0-9])\s*[..、、::]', "", item)
  435. return item
  436. def html_cleal_test(htmlf): # 不用
  437. html2txt = re.sub(r"&nbsp;", "", htmlf.read()) # ("", " ")
  438. # html2txt.replace("①", "(1).").replace("②", "(2).").replace("③", "(3).")
  439. con_list = [re.sub(r"^\n+\s+<p>", "", ii) for ii in html2txt.split("</p>")[:-1]]
  440. # pprint(con_list)
  441. if re.search(r"[\u4e00-\u9fa5]", con_list[0]) is None:
  442. con_list = con_list[1:]
  443. return con_list
  444. def get_md5(image_id):
  445. """
  446. 由于hash不处理unicode编码的字符串(python3默认字符串是unicode)
  447. 所以这里判断是否字符串,如果是则进行转码
  448. 初始化md5、将image_name进行加密、然后返回加密字串
  449. """
  450. image_name = str(image_id) + str(time.time()) + str(random.random())
  451. image_name = image_name.encode("utf-8")
  452. md = hashlib.md5()
  453. md.update(image_name)
  454. return str(md.hexdigest())
  455. def wash_after(res_dict, item_groups, ans_groups, subject):
  456. """
  457. 1.处理最终结果多余的换行符;2.对题文中已给答案的选择填空进行替换;3.选择题的细分
  458. :param res_dict: [{},{},,,]
  459. :param item_groups: 题组; ans_groups: 答案分组
  460. :return:
  461. """
  462. pattern1 = re.compile(
  463. r"([是为点]|等于|=|=|有|存在)\s*_+((<img src=((?!/>).)*?/>|[^_;;。?!,\n])+?)(?<![==_])_+([cdkm上]?m?\s*.?[。.?]?\s*"
  464. r"($|<br/>|<img src|……))")
  465. pattern2 = re.compile(r"((有|存在|[是为])[\u4e00-\u9fa5]{0,2})\s*_+(\d+)_+\s*([\u4e00-\u9fa5,,;;。..])")
  466. chapter_no = {}
  467. option_st = 0
  468. is_optional = False
  469. option_score = 0
  470. select_type_id = []
  471. for num, sr in enumerate(res_dict):
  472. sr["stem"] = re.sub(r"\n[_\-\s]*密[…O•.\s]*封[….O•\s]*装?[…O•.\s]*订?[….O•\s]*线?"
  473. r"|\n\s*((学校|班级|姓名|座位?号|准考号|学号)[\s::_]*){2,}", "", sr["stem"])
  474. sr["stem"] = re.sub(r'\n\s*(第\s*[^\s]\s*卷|第[一二三四]部分)\s*([((].*?[))]|非?选择题.{,8})?\s*\n', "\n", sr["stem"])
  475. if num == len(res_dict) - 1: # 对拆分后的最后一道题进行特殊判断
  476. end_con = sr["stem"] + sr["parse"]
  477. if len(re.findall(r"[\u4e00-\u9fa5]", end_con)) > 1000 and (
  478. len(re.findall(r"\n\s*([1-9]|1[0-9])\s*[..、、].+?",
  479. end_con)) > 4 or len(re.findall(r"[((]\s*[))]|_{2,}", end_con)) > 6):
  480. sr['errmsgs'].append("原试卷格式有问题,导致本题可能包含了很多非本题的题文")
  481. # if not re.sub(r"[(())\n\s]", "", sr["stem"]):
  482. # sr['errmsgs'].append("本题没有题干,请检查题干格式是否正确")
  483. if "-" in str(sr["item_id"]) and sr['type'] in ["选择题", "填空题"]:
  484. if (not sr["key"] or sr["key"] == "见解析") and re.search("[A-H]+", re.sub("[;;、、\n(())\s]|\d+分", "", sr["parse"])):
  485. sr["key"] = re.sub("[;;、、\n(())\s]|\d+分", "", sr["parse"])
  486. sr["parse"] = ""
  487. # 把首尾的换行都去掉
  488. # sr["stem"] = table_label_cleal(re.sub(r"\n\s*","<br/>",sr.get("stem", "").lstrip()))
  489. # 将选择题和填空题中的题干中出现答案的情况 去掉答案
  490. kuo_con1 = re.search(r'([是为]|等于|[==有]|表示)\s*[((]\s*([A-Zc][A-Zc;;和与、、\s]*?)[))]\s*(.?($|\n|<br/>|<img))',
  491. sr["stem"])
  492. kuo_con2 = re.search("[((]\s*([A-Zc][A-Zc;;和与、、\s]*?)[))]\s*(.?($|\n|<br/>))", sr["stem"])
  493. if sr['type'].replace("题", "") in ["单选", "多选", "选择", "不定选择"]:
  494. # sr["type"] = "选择类"
  495. # 针对选择题在题文中已给出答案的处理
  496. if kuo_con1:
  497. sr["stem"] = sr["stem"].replace(kuo_con1.group(0), kuo_con1.group(1) + "( )" + kuo_con1.group(3))
  498. sr["key"] = kuo_con1.group(2).replace("c", "C") if not sr["key"] else sr["key"]
  499. elif kuo_con2:
  500. sr["stem"] = sr["stem"].replace(kuo_con2.group(0), "( )" + kuo_con2.group(2))
  501. sr["key"] = kuo_con2.group(1).replace("c", "C") if not sr["key"] else sr["key"]
  502. # sr['options_text'] = ""
  503. elif sr['type'] == '填空题':
  504. # sr["type"] = "解答类"
  505. ans_list = []
  506. # 针对填空题在题文中已给出答案的处理
  507. sub_n = 0
  508. while re.search(pattern1, sr["stem"]):
  509. blank_con1 = re.search(pattern1, sr["stem"])
  510. sr["stem"] = sr["stem"].replace(blank_con1.group(0),
  511. blank_con1.group(1) + "____" + blank_con1.group(5))
  512. ans_list.append(blank_con1.group(2))
  513. sub_n += 1
  514. if sub_n > 5:
  515. break
  516. while re.search(pattern2, sr["stem"]):
  517. blank_con2 = re.search(pattern2, sr["stem"])
  518. # 这里的限制条件易出错,可以再判断一下
  519. sr["stem"] = sr["stem"].replace(blank_con2.group(0),
  520. blank_con2.group(1) + "____" + blank_con2.group(4))
  521. ans_list.append(blank_con2.group(2))
  522. if re.findall(r"_{2,}", sr["stem"]):
  523. sr["blank_num"] = len(re.findall(r"_{2,}", sr["stem"]))
  524. if not sr["key"] and ans_list:
  525. sr["key"] = "; ".join(ans_list)
  526. # 换行符处理!
  527. sr["stem"] = sr.get("stem", "").rstrip()
  528. # sr["stem"] = get_equation_instr(sr["stem"])
  529. if "options" in sr: # 对选项部分进行格式处理
  530. for i in range(len(sr['options'])):
  531. sr['options'][i] = get_simpstr2eqn(sr['options'][i].strip())
  532. # sr['options'][i] = get_equation_instr(sr['options'][i].strip()).replace("\n\n", "\n").replace("\n", "<br/>")
  533. if "slave" in sr and sr["slave"]:
  534. # 带小题的大题,格式处理,高中数学没有这一功能
  535. for s in sr["slave"]:
  536. s["stem"] = s.get("stem", "").rstrip()
  537. s["parse"] = s.get("parse", "").strip().replace("解答:解:", "解答:").replace("解答:解:", "解答:")
  538. s["key"] = s.get("key", "").strip()
  539. # sr["slave"] = sr.get("slave", "").replace("\n", "<br>")
  540. else:
  541. # s["parse"] = css_conflict_deal(s["parse"]) # "css 冲突标签处理"
  542. sr["parse"] = sr.get("parse", "").lstrip()
  543. sr["parse"] = re.sub("^【解[答析]】\s*", "", sr["parse"])
  544. # sr["parse"] = get_equation_instr(sr["parse"])
  545. sr["key"] = sr.get("key", "").lstrip()
  546. # sr["key"] = get_equation_instr(sr["key"])
  547. if not sr["parse"] and not sr["key"]: # 答案和解析都没有
  548. sr["parse"] = ""
  549. sr["key"] = ""
  550. # sr['errmsgs'].append("本题缺少答案和解析")
  551. elif not sr["key"] and sr["parse"]:
  552. sr["key"] = "见解析"
  553. elif re.sub("见解析|略|空|无|没有|答案", "", sr["key"]) and not sr["parse"]:
  554. sr["parse"] = ""
  555. # if "本选做题缺少解析" not in sr['errmsgs'] and "本题缺少解析" not in sr['errmsgs']:
  556. # sr['errmsgs'].append("本题缺少解析")
  557. # 辅助标签处理
  558. # sr["analysis"] = ""
  559. if "analy" in sr: # 存在题目分析时,将其放在解析里
  560. # sr["analy"] = sr.get("analy", "").strip().replace("\n\n", "\n")
  561. if len(sr["analy"].replace(" ", "")) >= 10:
  562. sr["parse"] = "【分析】"+sr["analy"] + "\n【详解】" + sr["parse"]
  563. del sr["analy"]
  564. if "chapter" in sr: # 如选修4-5:不等式选讲
  565. if sr['item_id'] + 1 <= len(res_dict):
  566. chapter_no[sr['item_id']] = sr["chapter"]
  567. del sr["chapter"]
  568. # 是否为选做题"is_optional",两种形式不会同时出现
  569. if "option_st" in sr: # 带有此标签的后面的题目都是选做题option_score
  570. # option_st = sr['item_id']
  571. # is_optional = True
  572. # if "," in sr["option_st"]:
  573. # option_score = int(sr["option_st"].split(",")[-1])
  574. del sr["option_st"]
  575. # 将选择题改为单选或多选,"is_multiple_choice"
  576. sr['type'] = re.sub("([单多])项选择题?", r"\1选题", sr['type'])
  577. sr['type'] = sr['type'].replace("题题", "题") # .replace("简答", "解答")
  578. # sr['type'] = re.sub("(计算|简答)题?", "解答题", sr['type'])
  579. if sr['type'] in ["选择", "选择题"]: # 有的科目只有选择题,不分单选和多选
  580. if len(re.findall("[A-Z]", sr["key"])) > 1:
  581. sr['type'] = '多选题'
  582. elif len(re.findall("[A-Z]", sr["key"])) == 1:
  583. sr['type'] = '单选题'
  584. info_x = re.search("^[((](多)选题?[))]", sr["stem"].replace(" ", ""))
  585. if info_x:
  586. sr['type'] = '{}选题'.format(info_x.group(1))
  587. # if "options" in sr:
  588. # sr['type'] = '选择'
  589. # else:
  590. # if re.search("_{2,}", str(sr)):
  591. # sr['type'] = '填空'
  592. # else:
  593. # sr['type'] = '解答'
  594. if sr['type'] == '多选题':
  595. if len(re.findall("[A-Z]", sr["key"])) == 1:
  596. sr['errmsgs'].append("本题答案个数与题型(多选题)不符")
  597. # sr["is_multiple_choice"] = 'true'
  598. elif sr['type'] == '单选题':
  599. # sr["is_multiple_choice"] = 'false'
  600. if "options" in sr and len(sr["options"]) > 4:
  601. sr['errmsgs'].append("选项个数多于4个,与题型(单选题)不符")
  602. if len(re.findall("[A-Z]", sr["key"])) > 1:
  603. sr['errmsgs'].append("本题答案个数与题型(单选题)不符")
  604. # elif sr['type'] == '不定选择题':
  605. # if len(re.findall("[A-Z]", sr["key"])) > 1:
  606. # sr['type'] = '多选题'
  607. # elif len(re.findall("[A-Z]", sr["key"])) == 1:
  608. # sr['type'] = '单选题'
  609. # else:
  610. # sr['type'] = '选择题'
  611. # if "缺少答案" not in "".join(sr['errmsgs']):
  612. # sr['errmsgs'].append("本题缺少答案")
  613. elif sr['type'].replace("题", "") in ["单空", "多空", "填空"]:
  614. sr['type'] = "填空题"
  615. elif subject != "语文" and sr['type'] not in ["选择", "选择题"]:
  616. sr['type'] = "解答题"
  617. # """按照原先高中数学解析的最后输出格式整理输出"""
  618. # sr["type"] = sr['type'].replace("非选择", "解答").replace("题题", "题") # print(“)
  619. sr["topic_num"] = sr['item_id']
  620. sr['errmsgs'] = ";".join(sr['errmsgs'])
  621. sr["parse"] = re.sub(r"试题【([分解]析)】", r"试题\1:", sr["parse"]) # 解析
  622. sr["key"] = re.sub("([;;]|<br/>)\s*$", "", sr["key"])
  623. if 'susp_pic' in sr:
  624. del sr['susp_pic']
  625. if 'is_optional' in sr:
  626. del sr['is_optional']
  627. if 'spliterr_point' in sr:
  628. del sr['spliterr_point']
  629. if 'score' in sr:
  630. del sr["score"]
  631. del sr['item_id']
  632. # ---------------------字符串公式处理--------------------------------
  633. # sr["stem"] = get_equation_instr(sr["stem"])
  634. # sr["key"] = get_equation_instr(sr["key"])
  635. # sr["parse"] = get_equation_instr(sr["parse"])
  636. # if "options" in sr:
  637. # sr["options"] = list(map(get_equation_instr, sr["options"]))
  638. # -----------------------------------------------------------------------
  639. # pprint(res_dict)
  640. if item_groups and item_groups["is_groups"]:
  641. # print("item_groups:", item_groups)
  642. # print("ans_groups:", ans_groups.keys())
  643. res_dict = stems_to_groups.regroup(res_dict, item_groups, ans_groups)
  644. else:
  645. for one_res in res_dict:
  646. one_res = parse_split2group(one_res)
  647. if "slave" in one_res and one_res["slave"]: # 带小问的试题题文也设置一下字体
  648. one_res['type'] = '小题多问类'
  649. one_res["stem"] = re.sub(r'(<p style="text-indent:.*?">\n*|<p style="text-align: center;?">\n*'
  650. r'|<p style="text-align: right;?">\n*)([^\n]+?)',
  651. r'\1<span style="font-family:楷体;">\2',
  652. one_res["stem"])
  653. elif "options" in one_res and one_res["options"]:
  654. one_res['type'] = '选择类'
  655. else:
  656. one_res['type'] = '解答类'
  657. if re.search("(阅读|针对|结合).{,4}[资材]料|(\n|^)\s*材料一\s", one_res['stem']):
  658. one_res["stem"] = re.sub(r'(<p style="text-indent:.*?">\n*|<p style="text-align: center;?">\n*'
  659. r'|<p style="text-align: right;?">\n*)([^\n]+?)',
  660. r'\1<span style="font-family:楷体;">\2',
  661. one_res["stem"])
  662. # pprint(res_dict)
  663. # 换行符替换
  664. convert_huanhang(res_dict)
  665. # ------------------------------------------------------------------------
  666. # if chapter_no: # 章节标签下移一位
  667. # for c, v in chapter_no.items():
  668. # res_dict[c]["chapter"] = v
  669. # 选做题"option_str"处理
  670. # if select_type_id:
  671. # for s in select_type_id:
  672. # if len(select_type_id) == 2:
  673. # res_dict[s - 1]['option_str'] = "2选1"
  674. # elif len(select_type_id) == 4:
  675. # res_dict[s - 1]['option_str'] = "4选2"
  676. # else:
  677. # res_dict[s - 1]['errmsgs'] += ";<br/>选做题不是“2选1”和“4选2”类型"
  678. # if option_st:
  679. # print("option_st:", option_st)
  680. # for s in range(option_st, len(res_dict)):
  681. # if (len(res_dict) - option_st) == 2:
  682. # res_dict[s]['option_str'] = "2选1"
  683. # elif (len(res_dict) - option_st) == 4:
  684. # res_dict[s]['option_str'] = "4选2"
  685. # else:
  686. # res_dict[s]['errmsgs'] += ";<br/>选做题不是“2选1”和“4选2”类型"
  687. # 再解析中的新图片上传腾讯云
  688. # 再设置一个入库接口,点击入库,才开始从本地上传图片
  689. return res_dict
  690. def convert_huanhang(items_list):
  691. """
  692. 递归 换行符替换:\n --> <br/>
  693. :param items_list:
  694. :return:
  695. """
  696. if isinstance(items_list, list):
  697. for k, one_i in enumerate(items_list):
  698. items_list[k] = convert_huanhang(one_i)
  699. elif isinstance(items_list, dict):
  700. for k, v in items_list.items():
  701. if k == "answer_type" and type(v) == str:
  702. items_list[k] = configs.answer_type[v]
  703. else:
  704. items_list[k] = convert_huanhang(v)
  705. elif isinstance(items_list, str):
  706. items_list = items_list.strip().replace("\n\n", "\n")
  707. items_list = re.sub('\n*(<p style=".*?">\n*)$', "", items_list)
  708. items_list = re.sub(r'(<p style=".*?">)\n+', r"\1", items_list)
  709. items_list = re.sub(r'(<p style=".*?">)(((?!</p>).)*?)\n+(</t[rd]>)', r"\1\2</p>\4", items_list)
  710. items_list = re.sub(r'(<p style=".*?">.+?)\n[\n\s]*(<img\s)', r"\1</p>\n\2", items_list)
  711. while re.search(r'(<p style=".*?">[^\n]+?)\n[\n\s]*(<p style=".*?">|<table>)', items_list, flags=re.S):
  712. items_list = re.sub(r'(<p style=".*?">[^\n]+?)\n[\n\s]*(<p style=".*?">|<table>)',
  713. r"\1</p>\2", items_list, flags=re.S)
  714. items_list = re.sub(r'(<p style=".*?">)(((?!</p>).)*?)\n*$', r"\1\2</p>", items_list)
  715. items_list = re.sub(r'(<span style="font-family:楷体;?">)(((?!</p>).)*?)</p>', r"\1\2</span></p>", items_list)
  716. # 将\n 换为 <p></p>
  717. items_list = linefeed2p(items_list)
  718. return items_list.replace("\n", "<br/>")
  719. else:
  720. return items_list
  721. return items_list
  722. def linefeed2p(item):
  723. """
  724. 换行标签替换为<p></p>标签,表格内的还需单独处理
  725. :return: str
  726. """
  727. # def subp_table(ss): # 表格里换行标签的处理,先看看情况是否需要处理
  728. if re.sub(r'<table>.*?</table>',"", item).count("\n") > 1:
  729. subs2table = {}
  730. all_table = re.findall(r'<table>.*?</table>', item, flags=re.S)
  731. for k, v in enumerate(all_table):
  732. subs2table["<t{}b>".format(str(k))] = v
  733. item = item.replace(v, "<t{}b>".format(k))
  734. lines = item.split("\n")
  735. newlines = [line if re.search(r"^<p style=|^<p>|</p>$", line) else "<p>{}</p>".format(line) for line in lines]
  736. item = "".join(newlines)
  737. if subs2table:
  738. item = re.sub(r"|".join(subs2table.keys()), lambda x: subs2table[x.group()], item)
  739. return item
  740. def css_conflict_deal(item):
  741. """
  742. 针对<a, <p 符号 在前端显示被过滤掉的问题:对“<”左右加$, 注意条件:“<”前$为双数时加,
  743. :return: str
  744. """
  745. # item = item.replace("<", "&lt;").replace(">", "&gt;") # 2021-8-24
  746. # item = re.sub("<(?!img src)", "&lt;", item) # 还有表格
  747. item = item.replace("$<$", "【*_*】")
  748. item = re.sub("<br\s*/?>", "\n", item)
  749. item = re.sub(r"<(/?su[bp])>", r"【\1】", item)
  750. item = re.sub(r"<(/?span|p style=|/?p>|/?strong>|/?em>)", r"【\1", item)
  751. if re.search(r"(?<!\\\()<", item):
  752. n1=0
  753. n2=0
  754. for i in re.finditer("<(?!img)", item):
  755. if item[:i.start()+2*n1+4*n2].count("$") % 2 == 0:
  756. item = item[:i.start()+2*n1+4*n2] + "$<$" + item[i.start()+1+2*n1+4*n2:]
  757. n1 += 1
  758. else:
  759. item = item[:i.start() + 2 * n1+4*n2]+" \lt " + item[i.start()+1+2*n1+4*n2:]
  760. n2 += 1
  761. item = item.replace("【*_*】", "$<$")
  762. while re.search(r"\\\(.*?\$<\$.*?\\\)", item):
  763. item = re.sub(r"(\\\(.*?)\$<\$(.*?\\\))", r"\1 \lt \2", item)
  764. item = re.sub(r"【(/?su[bp])】", r"<\1>", item)
  765. item = re.sub(r"【(/?span|p style=|/?p>|/?strong>|/?em>)", r"<\1", item)
  766. return item
  767. def insert_sort2get_idx(item_list, num):
  768. """
  769. :param item_list: 拍好序的列表
  770. :param num: 插入的数值
  771. :return: 插入的位置
  772. """
  773. add_n = 0
  774. for i in range(len(item_list)):
  775. if num > item_list[i]:
  776. add_n += 1
  777. else:
  778. break
  779. return add_n
  780. # def find_seq_num(num_list):
  781. # """
  782. # 针对切分题号时切错的序号进行纠正,考虑序号是连续且正常的情况下
  783. # 将连续的数字进行分组
  784. # :param num_list:输入[3, 4, 8, 9, 12, 13, 14]
  785. # :return: [[3, 4],[8, 9],[12, 13, 14]]
  786. # """
  787. # seq_ranges = []
  788. # for k, g in groupby(enumerate(num_list), lambda x: x[0] - x[1]):
  789. # group = (map(itemgetter(1), g))
  790. # group = list(map(int, group))
  791. # seq_ranges.append(group)
  792. # return seq_ranges
  793. # def del_exception_value(item_list):
  794. # """
  795. # 去列表中的异常值,题目越多,越容易突出异常值
  796. # :return:
  797. # """
  798. # import numpy as np
  799. # max_v = max(item_list)
  800. # arr_mean = np.mean(item_list) # 均值
  801. # arr_var = np.var(item_list) # 方差
  802. # while max_v > len(item_list)+4:
  803. # item_list.remove(max_v)
  804. # print(item_list)
  805. # arr_mean = np.mean(item_list) # 去最大值后的均值
  806. # arr_var = np.var(item_list) # 去最大值后的方差
  807. # max_v = max(item_list)
  808. # # print("均值与方差:",arr_mean,arr_var)
  809. # if abs((item_list[-1] - item_list[0] + 1) - len(item_list)) <= 3:
  810. # return item_list
  811. # else:
  812. # exception_value = []
  813. # for i in item_list:
  814. # # print(abs((i - arr_mean) / arr_var), i)
  815. # if(abs((i - arr_mean)/arr_var)) > 0.3:
  816. # exception_value.append(i)
  817. # right_seq = [i for i in item_list if i not in exception_value]
  818. # return right_seq
  819. def pic_transfer(con_list):
  820. aft_opt = [] # 针对选项后是题目图片的情况,进行移位
  821. if "\n" in con_list[-1]:
  822. ccon = re.split("\n+", con_list[-1])
  823. while re.match("<img src=", ccon[-1]) and len(ccon) > 1:
  824. aft_opt.insert(0, ccon[-1])
  825. ccon = ccon[:-1]
  826. if aft_opt:
  827. con_list[0] += "\n" + "\n".join(aft_opt)
  828. con_list[-1] = "\n".join(ccon)
  829. con_list[0] = re.sub(r"\(\d+分\)", "", con_list[0][:9]) + con_list[0][9:]
  830. return con_list
  831. def judge_split_error(item_list):
  832. """
  833. 转对试卷切分后的小题判断是否存在切分错误的情况,能纠错就纠错,不能则删除
  834. :return:
  835. """
  836. # for k, v in enumerate(item_list):
  837. # if k>0 and v['item_id'] - item_list[k-1]['item_id']>1:
  838. # if
  839. if __name__ == '__main__':
  840. # -------------生成requirements.txt---------------
  841. # pip freeze > requirements.txt
  842. # import os, sys
  843. #
  844. # project_root = os.path.dirname(os.path.realpath(__file__)) # 找到当前目录
  845. # print(project_root)
  846. #
  847. # # 找到解释器,虚拟环境目录
  848. # python_root = sys.exec_prefix
  849. # print(python_root)
  850. #
  851. # # 拼接生成requirements命令
  852. # command = python_root + '\Scripts\pip freeze > ' + project_root + '\\requirements.txt'
  853. # print(command)
  854. #
  855. # # 执行命令。
  856. # os.system(command)
  857. # ----------------一键安装 requirements.txt------------
  858. # pip install -r requirement.txt
  859. # python_root + '\Scripts\' + pip install -r requirements.txt
  860. # import os
  861. # rrr=os.path.basename(r"http:/pstatic.dev.xueping.com/data/word/2020/08/12/5f338d18e2cce.docx")
  862. # print(rrr)
  863. # item = "<a 我没发你的接口 $2366<a$ <a 我没发你的接口 $2366<a$ <img 我没发你的接口 $2366<a$ <a 我没发你的接口 $2366<a$ <a 我没发你的接口 $2366<a$"
  864. # item = r"2.下列选项中,使不等式\( x<\frac{1}{x}< x_{2} \)"
  865. # ww = css_conflict_deal(item)
  866. # print(ww)
  867. # -----------------
  868. p1 = r"C:\Users\Administrator\Desktop\temp\62314b31a7d375f4518b9afd.html"
  869. # t1 = open(p1,'r',encoding="utf8").read()
  870. t1 = """
  871. <p>7.南洋劝业会是1910年中国在南京举办的第一个世界博览会,历时达半年,中外30多万人参观。如表是南洋劝业会“物产会”展品目录,由此可知</p>
  872. <table border="1">
  873. <tbody>
  874. <tr>
  875. <td>
  876. <p>&nbsp;</p>
  877. </td>
  878. <td>分类</td>
  879. <td>具体内容</td>
  880. </tr>
  881. <tr>
  882. <td rowspan="6">天产品</td>
  883. <td>农业部</td>
  884. <td>五谷、园蔬、树艺、储藏、器具、肥料、水利、益虫害虫标本</td>
  885. </tr>
  886. <tr>
  887. <td>蚕桑部</td>
  888. <td>茧、丝、桑种标本、蚕种标本、器具、场室模型</td>
  889. </tr>
  890. <tr>
  891. <td>水产部</td>
  892. <td>麟醫、介甲、两栖、腔囊、植物、储藏、器具、舟船模型</td>
  893. </tr>
  894. <tr>
  895. <td>药材部</td>
  896. <td>植物、动物、金石、制合器具、储藏器具</td>
  897. </tr>
  898. <tr>
  899. <td>矿采部</td>
  900. <td>五金、石炭、杂矿、采矿器具、炼冶器具、山场模型</td>
  901. </tr>
  902. <tr>
  903. <td>狩猎部</td>
  904. <td>皮革、牙角、毛羽、器械、各种标本</td>
  905. </tr>
  906. <tr>
  907. <td rowspan="8">工艺品</td>
  908. <td>染织部</td>
  909. <td>漂染、机织、机器、场舍模型</td>
  910. </tr>
  911. <tr>
  912. <td>服装部</td>
  913. <td>衣服、冠履、带配、陈设、装饰、各种制造之器具</td>
  914. </tr>
  915. <tr>
  916. <td>陶磁(瓷)部</td>
  917. <td>陶器、磁(瓷)器、土器、制造器具、窑厂模型</td>
  918. </tr>
  919. <tr>
  920. <td>髹漆部</td>
  921. <td>雕填、磨甸、彩绘、八宝、器具、工场模型</td>
  922. </tr>
  923. <tr>
  924. <td>琉璃、珐琅部</td>
  925. <td>琉璃、珐琅、景泰蓝、荡磁(瓷)</td>
  926. </tr>
  927. <tr>
  928. <td>竹木、笺扇部</td>
  929. <td>竹器、木器、藤器、柳条器、竹簧器、笺纸、扇、画纸</td>
  930. </tr>
  931. <tr>
  932. <td>玉石部</td>
  933. <td>玉器、石器、器具、工场模型</td>
  934. </tr>
  935. <tr>
  936. <td>牙角、鞣革部</td>
  937. <td>牙器、角器、骨器、马尾器、牛革器、马革器、羊革器、鹿革器</td>
  938. </tr>
  939. </tbody>
  940. </table>
  941. <p>A.工业体系已经形成B.精耕细作持续繁荣</p>
  942. <p>C.近代工业发展缓慢D.经济推动文化变迁</p>
  943. <p>【答案】C</p>
  944. """
  945. res = HtmlWash(t1,'11111111',"高中物理").html_cleal()
  946. print(res)