washutil.py 46 KB

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