washutil_for_DL_way.py 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496
  1. #!/usr/bin/env/python
  2. # -*- coding:utf-8 -*-
  3. import re
  4. import base64, os, random
  5. import time
  6. from pprint import pprint
  7. import configs
  8. from utils.field_eq2latex import get_latex
  9. from utils.html_again_parse import css_label_wash
  10. def table_label_cleal(con):
  11. """
  12. 去掉表格中的【换行符】
  13. """
  14. # print(con)
  15. # print('------------------------------------------')
  16. con = re.sub(r"\n(\s|\n|\t)+", "\n", con)
  17. count = 1
  18. while re.search(r"</?[a-z]+>\n(</?[a-z]+>|<td\s+\n*[a-z=\"\d]+>)", con, re.S) and count <= 10:
  19. con = re.sub("(</?t[dr]>|</?table>|</?tbody>|</?div>)\n(</?t[dr]>|</div>|</?table>|</?tbody>|<p>)",
  20. r"\1\2", con, flags=re.S)
  21. con = re.sub(r'(</?t[rd]>)\n(<td\s.+?>)', r'\1\2', con, flags=re.S)
  22. count += 1
  23. # if re.search(r"<table>(.|\n)+?</table>", con, re.S|re.M):
  24. # aa = re.search(r"(<table>(.|\n)+?</table>)", con, re.S|re.M)
  25. # con = con.replace(aa.group(1),aa.group(1).replace("\n",""))
  26. # 将空表格的情况去掉
  27. 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>'
  28. r'[\s\n\t]*?</td>[\s\n\t]*?</tr>[\s\n\t]*?)+</tbody>[\s\n\t]*?</table>[\s\n\t]*?<p>', "", con,
  29. flags=re.S)
  30. con = re.sub(r'(</table><p>)\s*([((]\s*\d\s*[))])', r'\1\n\2', con)
  31. return con
  32. def base642img(html_data, wordid):
  33. """
  34. 【基于mathjax渲染输出是css-html格式】
  35. 将base64编码的图片保存到本地
  36. :return:
  37. """
  38. # 二进制图片进行转化, 按“word_id”建立文件夹
  39. # time_str = datetime.datetime.strftime(datetime.datetime.now(), '%Y_%m_%d')
  40. # file_path = configs.IMG_FOLDER + '/' + str(self.wordid)
  41. # if not os.path.exists(file_path):
  42. # os.makedirs(file_path)
  43. # else:
  44. # 思路1:删除图片,重建文件夹,【所有的新图片都是以base64格式传过来的】
  45. # shutil.rmtree(file_path)
  46. # os.makedirs(file_path)
  47. # 思路2:每一次再解析都将base64图片保存到本地再以路径形式返回
  48. # st = len(os.listdir(file_path)) # 不要以序号索引的形式命名
  49. # 统计所有base64编码
  50. all_base64_image = re.findall(r'(<img ([a-z]+="[^"]*?" )?src="(data:image[^>"]+?)"(.*?)\s*/?>)', str(html_data),
  51. flags=re.S)
  52. if all_base64_image:
  53. file_path = configs.IMG_FOLDER + '/' + str(wordid)
  54. if not os.path.exists(file_path):
  55. os.makedirs(file_path)
  56. # 新图片命名
  57. name_list = random.sample(range(100000, 999999), len(all_base64_image))
  58. for n, img in enumerate(all_base64_image):
  59. img1 = img[2].split(",", maxsplit=1)
  60. img_type_info = re.search("data:image/(.+?);base64", img1[0])
  61. img_type = img_type_info.group(1) if img_type_info else ""
  62. # 可能还有alt和style的属性,暂时先不要
  63. w_info = re.search('( width="\d+")', img[3])
  64. h_info = re.search('( height="\d+")', img[3])
  65. img_data = base64.b64decode(str(img1[-1]))
  66. if img_type:
  67. # save_path = os.path.join(configs.new_img_ip, get_md5(n)+"."+img_tape)
  68. img_name = "new_image" + str(int(time.time())) + str(name_list[n]) + "." + img_type
  69. save_path = os.path.join(file_path, img_name)
  70. with open(save_path, 'wb') as f:
  71. f.write(img_data)
  72. # self.localnewpic_list.append(save_path)
  73. # put_key = "/zyk/uploadfiles/wording/" + str(self.wordid) + "/{}".format(img_name)
  74. # self.put_key_list.append(save_path)
  75. flag_behind = '" />'
  76. if w_info and h_info:
  77. flag_behind = '"' + w_info.group(1) + h_info.group(1) + ' />'
  78. temp_img = '<img src="' + configs.new_img_ip + '/' + str(wordid) + '/' + img_name + flag_behind
  79. # new_img = '<img src="http://' + configs.public_bucket_addr + put_key + '" />'
  80. html_data = html_data.replace(img[0], temp_img)
  81. return html_data
  82. class HtmlWash_2():
  83. def __init__(self, html, wordid, is_reparse=0, img_url="", must_latex=0):
  84. """
  85. html文本清洗
  86. 批量再解析中,新增图片信息替换的文本返回作为ocr保存文本,
  87. 继续往下清洗的文本,则进入结构化解析逻辑中
  88. """
  89. # super().__init__(html, wordid, is_reparse, must_latex)
  90. self.html = html
  91. self.img_url = img_url
  92. self.wordid = wordid
  93. self.is_reparse = is_reparse
  94. self.must_latex = must_latex
  95. # self.put_key_list = []
  96. # self.localnewpic_list =[]
  97. self.sub_list = ["</?div>", "</?b>", "</?caption>", "</?center>", "</?cite>", "</?code>", "</?colgroup>",
  98. "</?menu>", "</?dd>", "</?dir>", "</?li>", "</?em>", "</?article>", "</?header>", "</?ruby>",
  99. "</?summary>", "</?details>", "</?strong>", "</?strike>", "</?small>", "</?select>",
  100. "</?section>", "</?script>", "</?[su]>", "</?var>", "</?ul>", "</?tt>", "</?title>",
  101. "</?thead>",
  102. "</?tfoot>", "<hr />", "<hr>", ""]
  103. self.sub_dd = {'&times;': '×',
  104. '&divide;': '÷',
  105. '&deg;': '°',
  106. '&middot;': '·',
  107. '&plusmn;': '±',
  108. '&ordm;': 'º',
  109. '&sup1;': '¹',
  110. '&sup2;': '²',
  111. '&sup3;': '³',
  112. '&frac12;': '1/2',
  113. '&frac14;': '¼',
  114. '&frac34;': '¾',
  115. '&yen;': '¥',
  116. 'm&sup3;': 'm³',
  117. # '&lt;': '<',
  118. '&pound;': '£',
  119. # '∠&lt;': '&lt;',
  120. '&gt;': '>',
  121. "A": "A",
  122. "А": "A",
  123. "Α": "A",
  124. "B": "B",
  125. "В": "B",
  126. "в": "B",
  127. "Β": "B",
  128. "C": "C",
  129. "С": "C",
  130. "c": "c",
  131. "с": "c",
  132. "D": "D",
  133. "Ε": "E",
  134. "E": "E",
  135. "F": "F",
  136. "G": "G",
  137. "g": "g",
  138. "m": "m",
  139. "N": "N",
  140. "s": "s",
  141. "t": "t",
  142. "/": "/",
  143. "=": "=",
  144. "-": "-",
  145. "2": "2", "3": "3", "4": "4", "5": "5", "6": "6",
  146. "7": "7", "8": "8", "9": "9", "1": "1", "0": "0",
  147. '&nbsp;&nbsp;': ' ',
  148. '&nbsp;': ' ',
  149. "〖": '【',
  150. "〗": '】',
  151. "題": '题',
  152. "单项选择": '单选',
  153. "多项选择": '多选',
  154. # "不定项选择": '选择',
  155. "双项选择": '多选',
  156. "实验与探究题": '实验',
  157. "原理综合题": '原理题',
  158. }
  159. def new_pic_sub(self):
  160. """
  161. 针对base64图片先保存到本地,入库时再换成腾讯云线上地址
  162. # 第一版:再解析中,将二进制图片进行转化,图片怎么保存比较好,先再“天数”建立文件夹
  163. 第一版:再解析中,根据“word_id”建立文件夹
  164. :return:
  165. """
  166. if self.is_reparse:
  167. # css 标签清洗
  168. self.html = css_label_wash(self.html)
  169. # 保存base64编码的图片
  170. self.html = base642img(self.html, self.wordid)
  171. self.new_html = self.html
  172. def html_cleal(self):
  173. # =======清洗mathjax标签========
  174. if "MathJax" in self.html: # 再解析中存在mathjax公式渲染的标签
  175. all_mathjax = re.findall('(<span class="MathJax_Preview".*?</script>(</span>)*)', self.html)
  176. for jax in all_mathjax:
  177. latex = re.findall('<script .+?">(((?!(</)).)*?)</script>(</span>)*', jax[0])
  178. if latex:
  179. latex = "${}$".format(latex[0][0])
  180. self.html = self.html.replace(jax[0], latex)
  181. else:
  182. self.html = self.html.replace(jax[0], "")
  183. # ======再解析中的新图片处理=====
  184. self.new_pic_sub()
  185. # =====特殊符号处理=====
  186. html2txt = re.sub(r"|".join(self.sub_list), "", str(self.html)) # ("", " ") #2020/4/7
  187. html2txt = re.sub("|".join(self.sub_dd.keys()), lambda x: self.sub_dd[x.group()], html2txt) # 2020/4/1,4/7,4/20
  188. html2txt = re.sub("[不非]定[向项]选择", "不定选择", html2txt)
  189. html2txt = html2txt.replace(r"\\[{\\text{V}}V\]", "Ⓥ").replace(r"\\[{\\text{A}}A\]", "Ⓐ") \
  190. .replace(r"\\[{\\text{W}}W\]", "Ⓦ").replace(r"\\[{\\text{X}}X\]", "Ⓧ").replace(r"\\[{\\text{G}}G\]", "Ⓖ") \
  191. .replace("\uf067", "γ").replace('', "γ").replace('\uf020', "").replace("\u3000", " ") \
  192. .replace("\u2003", " ").replace("\x7f", " ").replace("\xa0", "")
  193. html2txt = re.sub(r"(<p>\s*)【例题(\d+)】", r"\1\2、", html2txt)
  194. html2txt = re.sub(r"\\\(|\\\)", "$", html2txt)
  195. # 域公式的转化处理;<sub>\<sup>可以在前端显示,不需要用latex渲染
  196. try:
  197. html2txt, newhml = get_latex(html2txt, self.is_reparse, self.wordid, self.must_latex)
  198. if newhml: # 存在域公式转图片时,需要将原文本的域公式也转为图片信息
  199. self.new_html = newhml
  200. html2txt = html2txt.replace("【omml-latex】", "")
  201. except:
  202. html2txt = html2txt.replace("【omml-latex】", "")
  203. # 字符串公式的处理:如Fe<sub>2</sub>O<sub>3</sub>, 在结构化之后处理比较好
  204. # <br/>处理
  205. html2txt = re.sub(r"<br\s*/?>", "\n", html2txt)
  206. html2txt = re.sub(r"[((]\s*(\d)\s*\$分\s*[))]", r"$(\1分)", html2txt)
  207. # =====题型行的统一处理=====
  208. # ---->>>>>题型行可能放在表格中
  209. if len(re.findall("</table>", html2txt)) >= 8: # 这个限制还不太严谨
  210. for tt in re.finditer('<tr>(((?!(</?tr>)).)*)</tr>', html2txt, re.S):
  211. tt_list = re.split(r'^\s*<td[^<>]*?>|</p></td>|</td>[\n\s]*?<td[^<>]*?>'
  212. r'|</td>\s*\n|</td>\s*$|\n\s*<td[^<>]*?>|<td[^<>]*?><p>',
  213. tt.group(1).strip()) # </td>\s*[$\n]这样无效
  214. tt_list = [col for col in tt_list if col.strip()]
  215. if " ".join(tt_list).replace(" ", "") in ['得分评卷人', '评卷人得分']:
  216. html2txt = html2txt.replace(tt.group(0), "")
  217. else:
  218. pass
  219. # html2txt = html2txt.replace(tt.group(0), "<p>" + " ".join(tt_list) + "</p>")
  220. # html2txt = re.sub(r"</?tbody>|</?table>|</?div>", "", html2txt)
  221. # ---->>>>>end
  222. html2txt = re.sub(r"(</table>)\s*([一二三四五六七八九十]\s*[、..、::]?.{2,6}题)", r"\1</p>\2", html2txt)
  223. html2txt = re.sub(r'([一二三四五六七八九十])\s*[、..、,,::]\s*(论述|填空|探究)题?[与和、、,,\s]*?(计算题|实验题)', r"\1、\3", html2txt)
  224. html2txt = re.sub(r'<td[^<>]*?><p>(([一二三四五六七八九十])\s*[、..、,,::]\s*(.{2,4}题)\s*</p>)</td>[^p]*?<p>', r"\1",
  225. str(html2txt), flags=re.S)
  226. html2txt = re.sub(r"<p>\s*([一二三四五六七八九十])\s*[、..、,,::]?\s*(计算|[解简]答|实验|作图)题?[与和、、,,\s]*?(计算|[解简]答|实验|作图)",
  227. r"<p>\1、\2题", html2txt)
  228. html2txt = re.sub(r'<p>\s*[((]\s*[一二三四五六]\s*[))]\s*必考题\s*(.?|.+?分\s*[.。.]?)\s*</p>', "", html2txt)
  229. html2txt = re.sub(r'<p>\s*[((]\s*[一二三四五六]\s*[))]\s*选考题\s*.?\s*.{,4}(?<!\d)(\d+分)\s*[,,。].{,50}</p>',
  230. r"<p>【选做题】:'\1'</p>", html2txt)
  231. html2txt = re.sub(r'<p>\s*[((]\s*[一二三四五六]\s*[))]\s*选考题\s*(.?|.+?分\s*[.。.]?)\s*</p>', "<p>【选做题】</p>", html2txt)
  232. html2txt = re.sub(r'<p>\s*([一二三四五六七八九十])\s*[、..、,,::]?\s*(单项?选择?|非?选择|多项?选择?|不定选择|填空|计算|[解简]答|实验|作图)题?\s*</p>',
  233. r"<p>\1、\2题</p>", html2txt)
  234. html2txt = re.sub(r'([一二三四五六七八九十])\s*[、..、,,::]?\s*(单选|单项选择|选择|不定选择|多选|多项选择|填空|计算|[解简]答|实验|作图)\s*(?!题)'
  235. r'([((]\s*本题|.*?\d分)', r"\1" + "、" + r'\2' + "题" + r"\3", html2txt)
  236. html2txt = re.sub(r'([一二三四五六])\s*[、..、,,::]?\s*(单选|单项选择|非?选择|不定选择|多选|多项选择|填空|计算|[解简]答|实验|作图)题',
  237. r"\1" + "、" + r'\2' + "题", html2txt)
  238. # html2txt = re.sub(r'([一二三四五六七八九十])\s*[、..、,,::]?\s*[((]\s*本大题(.*?选项中)', r"\1" + "、" + "选择题", html2txt) # + r"\2"
  239. # html2txt = re.sub(r'<p>\s*([一二三四五六七八九十])\s*[、..、,,]?\s*[((本大题]*?(.*?选项中)', r"\1" + "、" + "选择题", html2txt)
  240. html2txt = re.sub(r'([一二三四五六七八九十])\s*[、..、,,::]?\s*([((]\s*(每小题|本大?题)((?!(选项)).)+?[))]|综合题)',
  241. r"\1" + "、" + "解答题", html2txt)
  242. html2txt = re.sub(r'(?<!<p>)\s*([一二三四五六七八九十]\s*[、..、,,::]?\s*(单项?选择?|选择|不定选择|多项?选择?|填空|计算|[解简]答|实验|作图)题)',
  243. r'</p>\n<p>\1', html2txt)
  244. html2txt = re.sub(r'<p>\s*([一二三四五六七八九十])\s*[、..、,,::]?\s*[((]?本?大?题((?!(选项)).)+?[))]?\s*</p>', r"<p>\1、本大题</p>",
  245. html2txt)
  246. # html2txt = re.sub(r'<p>\s*[^一二三四五六七八九十]{,3}\s*[、..、]\s*(选择|不定选择|单选|多选|计算|[解简]答|实验|作图)题', r"<p>一、\1题", html2txt)
  247. # =====图片的处理=====
  248. # 1>>根据图片宽高的异常值判断删除隐藏图片
  249. def sub1(ss):
  250. if float(ss.group(1)) <= 3 and float(ss.group(2)) <= 3:
  251. return ""
  252. else:
  253. return ss.group(0)
  254. html2txt = re.sub(r'<img src=.*? width="([\d.]+)p[xt]" height="([\d.]+)p[xt]"\s*/?>', sub1, html2txt)
  255. # 2>>将图片中带有的汉字去掉
  256. html2txt = re.sub(r'(<img src=.*?) alt=".+?"', r"\1", html2txt)
  257. # html2txt = re.sub(r'(<img src=.+?(?<!\\)\")>', r"\1 />", html2txt) # 将">换为" />
  258. html2txt = re.sub(r'(<img src=(?!\sstyle=)+?(?<!\\)\")>', r"\1 />", html2txt) # 将">换为" />
  259. # =====答案解析关键字的统一处理=====
  260. html2txt = re.sub(r'【\s*(<img src=((?!/>).)+?/>\s*)*?([解答])\s*(<img src=((?!/>).)+?/>\s*)*?([析案])\s*'
  261. r'(<img src=((?!/>).)+?/>\s*)*?】', r"【\3\6】", str(html2txt)) # 2022/4/28
  262. html2txt = re.sub(r'<p>\s*(解\s*[::])', r"<p>【解答】", str(html2txt))
  263. html2txt = re.sub(r'【[^【】]*?(答案|[解分][析答]|详解|点[评睛])[^【】]*?】', r"【\1】", str(html2txt))
  264. # html2txt = re.sub(r'【[^【】]*?(答案|[解分][析答])[^【】]*?】', r"【\1】", str(html2txt))
  265. html2txt = re.sub(r'(\n\s*|<p>\s*|\s{2,}|\n\s*\d{,2}\s*[、..、]\s*)(答案|解析|解答|详解|点评|点睛|考点|专题)\s*[::]', r"\1【\2】",
  266. str(html2txt))
  267. html2txt = re.sub(r'(\n|^|<p>)\s*(([1-9]|[1-9][0-9])\s*[..、、])?\s*\[\s*(答案|解析|解答|详解|点评|点睛|考点|专题)\s*\]',
  268. r"\1\2【\4】", str(html2txt))
  269. html2txt = re.sub(r'([A-D])\s*\[\s*(解析|解答|详解|点评|点睛|考点|专题)\s*\]', r"\1\n【\2】", str(html2txt))
  270. html2txt = re.sub(r'(\n|^|<p>)\s*(分析)\s*[::]', r"【\2】", str(html2txt))
  271. if "【解析】" not in html2txt and "【解答】" in html2txt and "【分析】" not in html2txt:
  272. html2txt = re.sub(r'【解答】', "【解析】", str(html2txt))
  273. # =====其他关键字的处理=====
  274. html2txt = re.sub(r'<p>\s*(类型|知识点|考查角度|拔尖角度)[一二三四五六七八九十\d+][^p]*?</p>', "", str(html2txt))
  275. html2txt = re.sub(r'<p>\s*(选修[\d-]*?[::].{2,15})\s*</p>', r"<p>【章节】\1</p>", html2txt)
  276. html2txt = re.sub(r'<p>\s*([一二三四五六]\s*[、..、]?)?\s*(\[.{2}-*?选修[\d-]*?.*?\])\s*([((]\d+分[))])?\s*</p>',
  277. r"<p>【章节】\2</p>", html2txt)
  278. html2txt = re.sub(r'<p>\s*(基础|中档|综合)题[^p题]*?</p>|<p>\s*【(考点|专题)】[^p]*?</p>', "", str(html2txt))
  279. html2txt = re.sub(r'<p>\s*(基础训练|提升训练|探究培优)</p>', "", str(html2txt))
  280. html2txt = re.sub(r'<p>注意事项[::]\s*</p>(\n+\s*<p>\s*\d\s*[、..、][^/]+?</p>){1,}', "", html2txt, flags=re.S)
  281. html2txt = re.sub(r'<p>注意事项[::]\s*\d\s*[、..、][^/]+?</p>(\n+\s*<p>\s*\d\s*[、..、][^/]+?</p>){1,}', "", html2txt,
  282. flags=re.S)
  283. html2txt = re.sub(r'[((]\s*([A-Z\dⅠⅡⅢⅣⅤ]+|IV)\s*[))]', r"(\1)".replace(" ", "").replace("(IV)", "Ⅳ"), html2txt)
  284. html2txt = re.sub(r'[((](\s*\d\s*\d?\s*分?\s*)[))]', "(" + r'\1'.replace(" ", "") + ")", html2txt)
  285. html2txt = re.sub(r'\[来源:.*?\]', "", html2txt)
  286. html2txt = re.sub('<p>欢迎访问.*?</p>', '', html2txt)
  287. html2txt = re.sub('w\s*w\s*w\..*?(\.\s*c\s*o\s*m|\.cn)+|(?<!["“=\'])http:.*?\.(com|cn|org)', "",
  288. html2txt) # ww w.gkstk.c om
  289. html2txt = re.sub(r'<(table|tr) [a-z]+="\d+">', r'<\1>', html2txt) # <td rowspan="2">保留
  290. html2txt = re.sub(r'<(table)( [a-z]+=".*?")+>', r'<\1>', html2txt)
  291. html2txt = re.sub(r'<p>\s*第\s*[二三四ⅡⅢⅣ]\s*(卷|部分)\s*([((].*?[))]|非?选择题.{,8})?\s*</p>', "<p>【非选择题】</p>", html2txt)
  292. # == == =对可能的题型行的处理 == ==
  293. html2txt = re.sub("<p>【非选择题】</p>((\s|\n|<p>|</p>)*\d{1,2}\s*[..、、].+?)", r"<p>二、解答题</p>\1", html2txt) \
  294. .replace("【非选择题】", "")
  295. # =====选项的处理=====
  296. html2txt = re.sub(r'(<p>\s*([1-9]|[1-9][0-9])\s*[..、、].+?[((]\s*[))])\s*(A\s*[..、、][^/]*?</p>)',
  297. r"\1</p>\n<p>\3", str(html2txt))
  298. # =====题号的处理=====
  299. html2txt = re.sub(r'([ED]\s*[、..、].*?((?<![::])\s+|</su[pb]>\s*))(([1-9]|[1-9][0-9])\s*[、..、])',
  300. r"\1</p>\n<p>\3", html2txt)
  301. html2txt = re.sub(r'((</?p>|\n)\s*(<img src=.*?"\s*/?>\s*)?([1-9]|[1-9][0-9]))\s*'
  302. r'([((]\s*(\d{1,2}[.\s\d]*?分|.{2,3}题?)\s*[))]|解析?\s*[::]|【解析】)', r"</p>\1、\5", html2txt)
  303. 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",
  304. html2txt)
  305. html2txt = re.sub(r"<p>\s*([1-9]|[1-9][0-9])\s*(【(解析?|答案?)】|(解析?|答案?)\s*[::]|\[(答案|解析)\])", r"<p>\1、\2",
  306. html2txt)
  307. html2txt = re.sub(r"<p>\s*([1-9]|[1-9][0-9])\s*([((]\s*\d+\s*分?\s*[))])?(【(解析?|答案?)】|(解析?|答案?)\s*[::]"
  308. r"|\[(答案|解析)\])", r"<p>\1、\2\3", html2txt)
  309. # 图片和题号相连情况
  310. html2txt = re.sub(r"<p>\s*(<img src=((?!/>).)+?/>)\s*([1-9]|[1-9][0-9])\s*"
  311. r"([((]20\d{2}\s*[\u4e00-\u9fa5、、]{2,9}[))])", r"<p>\3、\1\4", html2txt) # 2024.5.6
  312. html2txt = re.sub(r'<p>((\s*<su[bp]>\s*)?<img src=.*? height="[\d.]+p[tx]"\s*/?>(\s*</su[bp]>)?\s*)'
  313. r'(([1-9]|[1-9][0-9])\s*[、..、])', r"<p>\4\1", html2txt) # 2024.5.6
  314. html2txt = re.sub(r"(</p>|\n)\s*(<img src=((?!/>).)+?/>)\s*([1-9]|[1-9][0-9])\s*"
  315. r"([((]20\d{2}\s*[\u4e00-\u9fa5、、]{2,9}[))])", r"<p>\2</p>" + "\n" + r"<p>\4、\5",
  316. html2txt) # 【susp_img】
  317. html2txt = re.sub(r'(</p>|\n)((\s*<su[bp]>\s*)?<img src=.*? height="[\d.]+p[tx]"\s*/?>(\s*</su[bp]>)?\s*)'
  318. r'(([1-9]|[1-9][0-9])\s*[、..、])', r"</p>\2</p>" + "\n" + r"\5", html2txt)
  319. html2txt = re.sub(r"(<p>((?!<p>).)+?(\s|[/\"]>))(([1-9]|[1-9][0-9])\s*[、..、].{,20}本[大小]?题\d+分)",
  320. r"\1</p>" + "\n<p>" + r"\4", html2txt)
  321. # 多张图片和题号相连情况
  322. html2txt = re.sub(r"</?p>((\s*<su[bp]>\s*)?<img src=.*?/>(\s*</su[bp]>)?"
  323. r"((\s*<su[bp]>\s*)?<img src=((?!/>).)+?/>(\s*</su[bp]>)?)*?\s*)\s*(([1-9]|[1-9][0-9])\s*[、..、])",
  324. r"</p>\1</p>" + "\n<p>" + r"\8", html2txt, flags=re.S)
  325. html2txt = re.sub(r'(<p>\s*[一二三四五六七八九十].*?题\s*\(.+?分.*?\))\s*(([1-9]|[1-9][0-9])\s*[、..、].*?)</p>',
  326. r"\1</p>\n<p>\2</p>", html2txt)
  327. html2txt = re.sub(r'(<p>\s*[一二三四五六七八九十].*?题\s*\(.+?分.*?\))\s*(([1-9]|[1-9][0-9])\s*[、..、].*?)</p>',
  328. r"\1</p>\n<p>\2</p>", html2txt)
  329. html2txt = re.sub(r'(<p>.*?[..]{6,}\s*\d+分)\s*(([1-9]|[1-9][0-9])\s*[、..、].*?)</p>', r"\1</p>\n<p>\2</p>",
  330. html2txt)
  331. html2txt = re.sub(r'([1-9]|[1-9][0-9])\s*([((]\s*\d{1,2}[.\s\d]*?分\s*[))])\s*[、..、]', r"\1" + "、" + r"\2",
  332. html2txt)
  333. # 3>>建立图片id字典,对原图片信息第一次替换
  334. html2txt = re.sub(r'( src=".*?files)\\image', r"\1/image", html2txt)
  335. # all_image = re.findall(r'<img src=".*?image[\da-z]+\..*?[/\"]>', html2txt)
  336. # src2subs = {}
  337. # subs2src = {}
  338. # for src in all_image:
  339. # # 校本题库上传的图片名称是随机数,故设置映射
  340. # # kk = re.search('(<img src=".*?image\d+\.(png|gif|jpg|jpeg))', src)
  341. # # new_src = src.replace(kk.group(1), self.img_url[kk.group(1)]) if type(self.img_url) == dict and kk else src
  342. # # 图片信息简化替换
  343. # print(src)
  344. # new_src = re.sub(r'( data-latex)="\s*\\\[(.*?)\\\]\s*"', r'\1="$\2$"', src)
  345. # new_src = re.sub(r'( data-latex="\$[^"]+?\$")',
  346. # lambda x: x.group(1).replace("<", " \lt ").replace(" ", " "), new_src)
  347. # latex_info = re.search(r'<img src=".*?/(new_)?image([\da-z]+)\..*?(data-latex=".*?")', src)
  348. # mathpix = " " + latex_info.group(3).replace("\n", "").strip().replace(" ", " ") if latex_info else ""
  349. # if mathpix and len(mathpix) > 20:
  350. # mathpix = ""
  351. # w_h_info = re.search(r'<img src=".*?/(new_)?image([\da-z]+)\..*?width="([\d.]+)[pxt]*?"\s*height="([\d.]+)[pxt]*?"', src)
  352. # w_h = " w_h=" + w_h_info.group(3).split('.')[0] + "*" + w_h_info.group(4).split('.')[0] \
  353. # if w_h_info and not mathpix else "" # w_h 和 mathpix只存在一个
  354. # # image_id = re.search(r'<img src=".*?/(new_)?image([\da-z]+)\.', src).group(2)
  355. # image_info = re.search(r'<img src=".*?/([^/]+?)/(new_)?image([\da-z]+)\.', src) # 2023.12.1
  356. # print(image_info.groups())
  357. # image_id = image_info.group(1) + image_info.group(3)
  358. # if len(image_id) > 10:
  359. # image_id = image_id[-10:]
  360. # src2subs[src] = '<imgsrc' + image_id + w_h + mathpix + "/>"
  361. # subs2src['<imgsrc' + image_id + w_h + mathpix + "/>"] = new_src
  362. # for k, v in src2subs.items():
  363. # html2txt = html2txt.replace(k, v)
  364. # ------------------------------------------------------------------------
  365. # ========html 转 list=========
  366. html2txt = re.sub(r'(</?div>|</table>|</?body>)(\n\s*)*?<p>', r"\1</p>" + "\n<p>", html2txt, flags=re.S)
  367. # >>>>>> <table>先替换后再切割
  368. # 不能简单按 \n 切割,表格里面也可能有换行,应该先替换后再切割
  369. subs2table = {}
  370. all_table = re.findall(r'<table>.*?</table>', html2txt, flags=re.S)
  371. for k, v in enumerate(all_table):
  372. html2txt = html2txt.replace(v, "<t{}b>".format(k))
  373. # 将表格中的换行去掉
  374. v = re.sub(r'<p>\s*(</?t[drh]( .*?")?>|</?table>|</?tbody>)\s*</p>', r"\1", v)
  375. v = re.sub(r'</td></p>[\n\s]*<p><td>', "</td><td>", v)
  376. v = re.sub(r'<td>(<p>|\s|</p>|\n)*</td>', "<td> </td>", v)
  377. v = re.sub(r'</tbody></?p></table>', "</tbody></table>", v)
  378. v = re.sub(r'(</?t[drh]( .*?")?>|</?table>|</?tbody>)(\s*<p>\s*</p>)[\s\n]*?(<br\s*/?>|\n)+', r"\1", v,
  379. flags=re.S)
  380. v = re.sub(r'(</?t[drh]( .*?")?>|</?table>|</?tbody>)(<br\s*/?>|\n|</p>|\s)+', r"\1", v, flags=re.S)
  381. v = re.sub(r'(</t[drh]( .*?")?>|</table>|</tbody>)(<br\s*/?>|\n|<p>|\s)+', r"\1", v, flags=re.S)
  382. # 暂时还有table标签首尾的换行没去掉
  383. subs2table["<t{}b>".format(str(k))] = v
  384. # <造成的css标签冲突处理 2021-10-13
  385. def sub2(ss):
  386. if re.search(r'^(img|/?h[123456]|/?su[bp]>|t\d+b>|br\s*/?>'
  387. r'|/?(p|span|font|article|ul|ol|div|table|t?body|html|head|t[drh])(\s*|\s+style=.*?")>'
  388. r'|/?[a-z]+ style=.*?">)', ss.group(1)) is None:
  389. return "&lt;{}".format(ss.group(1))
  390. else:
  391. return "<{}".format(ss.group(1))
  392. html2txt = re.sub("<([^<]{1,30})", sub2, html2txt)
  393. if subs2table:
  394. html2txt = re.sub(r"|".join(subs2table.keys()), lambda x: subs2table[x.group()], html2txt)
  395. # print(html2txt)
  396. # >>>>>> html 切割
  397. con_list = sum([re.split('<p>|<h[12345]>', i) if len(re.findall("<p>|<h[12345]>", i)) > 1 else [i] for i in
  398. re.split(r"\n+|</p>(?!</td>)|</h[12345]>", html2txt)], []) # html2txt)[:-1]
  399. con_list = [re.sub(r"^\n*\s*(<p>|<h[12345]>)+", "", 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*<imgsrcw_h=[^/\"]*?(data-latex=.*?)?\s*[/\"]>\s*)+)", v.strip(), maxsplit=1)[1::3]
  410. if re.match(r'(\s*<imgsrcw_h=[^/\"]*?(data-latex=.*?)?\s*[/\"]>\s*)+?(参考|考试|试[题卷]|物理|理综|数学|化学|生物)(答案|解析|答案[及与和]评分(标准|意见|细则))\s*$'
  411. r'|(\s*<imgsrcw_h=[^/\"]*?(data-latex=.*?)?\s*[/\"]>\s*)+?评分标准'
  412. r'|(\s*<imgsrcw_h=[^/\"]*?(data-latex=.*?)?\s*[/\"]>\s*)+?(参考|考试|试[题卷])(答案|解析|答案[及与和]评分(标准|意见|细则))\s*(物理|理综|数学|化学|生物)?\s*$',
  413. re.sub(r"[上下]?学[年期]|[\d—【】..、、::(())年\s]|[中大]学|模拟|[中高]考|年级|[学期][末中]|[高初][一二三]", "",
  414. v.strip())) else [v] for v in con_list]
  415. con_list = sum(temp_list, [])
  416. # =====对可能的题号的处理==== 如2、3、4、5、 加了【fei】 # 重新修改!!!!!!!!!!
  417. con_list = [re.sub(r"^\s*([1-9][0-9]?\s*[..、、])", r"【fei】\1", i.strip())
  418. if (len(re.findall(r"(^|\s*[..、、])\s*[1-9][0-9]?\s*[..、、]", i)) >= 3
  419. and len(re.sub(r"[\d..、、\s]", "", i)) < 2) else i for i in con_list]
  420. # =====头尾清除没用的信息=====
  421. if con_list and re.search(r"[\u4e00-\u9fa5]|<img ", con_list[0]) is None:
  422. con_list = con_list[1:]
  423. while con_list and re.search(r"声明[::].*?著作权属.*?所有|(邮箱|用户|日期|QQ)\s*[::].+?", con_list[-1]):
  424. con_list = con_list[:-1]
  425. return html2txt, con_list, self.new_html # subs2table
  426. if __name__ == '__main__':
  427. # -------------生成requirements.txt---------------
  428. # pip freeze > requirements.txt
  429. # import os, sys
  430. #
  431. # project_root = os.path.dirname(os.path.realpath(__file__)) # 找到当前目录
  432. # print(project_root)
  433. #
  434. # # 找到解释器,虚拟环境目录
  435. # python_root = sys.exec_prefix
  436. # print(python_root)
  437. #
  438. # # 拼接生成requirements命令
  439. # command = python_root + '\Scripts\pip freeze > ' + project_root + '\\requirements.txt'
  440. # print(command)
  441. #
  442. # # 执行命令。
  443. # os.system(command)
  444. # ----------------一键安装 requirements.txt------------
  445. # pip install -r requirement.txt
  446. # python_root + '\Scripts\' + pip install -r requirements.txt
  447. # import os
  448. # rrr=os.path.basename(r"http:/pstatic.dev.xueping.com/data/word/2020/08/12/5f338d18e2cce.docx")
  449. # print(rrr)
  450. # item = "<a 我没发你的接口 $2366<a$ <a 我没发你的接口 $2366<a$ <img 我没发你的接口 $2366<a$ <a 我没发你的接口 $2366<a$ <a 我没发你的接口 $2366<a$"
  451. # item = r"2.下列选项中,使不等式\( x<\frac{1}{x}< x_{2} \)"
  452. # ww = css_conflict_deal(item)
  453. # print(ww)
  454. p1 = r"/home/cv/workspace/tujintao/document_segmentation/Data/samples/真实样例/6264fa25f84c0e279ac643ef.html"
  455. t1 = open(p1, 'r', encoding="utf8").read()
  456. row_list, new_html = HtmlWash_2(t1, '11111111', is_reparse=1, must_latex=1).html_cleal()
  457. row_list = list(filter(lambda x: x.strip() != "", row_list))
  458. pprint(row_list)
  459. print(len(row_list))
  460. # html, wordid, is_reparse=0, img_url="", must_latex=0)