formula_extract_lqy2.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  1. # -*- coding: utf-8 -*-
  2. import re
  3. import regex as rex
  4. from math_reg_sever.is_double_kuohao import is_double_kuohao
  5. def find_serial_sm(one_mp_item):
  6. """
  7. 找出其中连续的数学符号序列
  8. :param one_mp_item: str,清洗后的,公式为maple的字符串,空字符串替换以后!!!
  9. :return: serial_sm:str,如果不存在这样的序列,则返回空字符串
  10. """
  11. serial_sm = "" # 连续的数学符号
  12. serial_sm_start = -1
  13. serial_sm_end = -1
  14. # item_kuo = is_double_kuohao(one_mp_item) #该题目本身括号是否正常
  15. for i, c in enumerate(one_mp_item):
  16. if serial_sm_end != -1 and i - serial_sm_end > 1:
  17. break
  18. b1 = re.match("[^#::??。∵∴..,,;;、ⅠⅡⅢⅣⅤ①②③④⑤\u4e00-\u9fa5]", c)
  19. b2 = (re.match(r"[,,;;::\u4e00-\u9fa5]", c) and
  20. not is_double_kuohao(serial_sm)) # <---整个题目本身括号如果不正常,就把,;:当分隔符分断
  21. b3 = re.match(r"[..]", c) and len(serial_sm) > 0 and re.match(r"\d", serial_sm[-1])
  22. if b1 or b2 or b3:
  23. if serial_sm_start == -1:
  24. # 数学公式一定是以大小写字母,数字,({<开头,其中<是向量那一块的
  25. if re.match(r"[({[<\da-zA-Z∠-△▵Δ∁ρθαβγφδεξλη|]", c):
  26. serial_sm_start = i
  27. serial_sm_end = serial_sm_start
  28. serial_sm += c
  29. else:
  30. if i == serial_sm_end + 1:
  31. serial_sm_end += 1
  32. serial_sm += c
  33. else:
  34. # serial_sm = ""
  35. break
  36. # ########是否为公式筛选######
  37. re_filter = False
  38. if sm_filter(serial_sm):
  39. serial_sm = "犇" # 不能置为"",如果置为"",下面循环找serial_sm的时候,就不会继续找后面的了
  40. else:
  41. m = re.search(r"(^\([1-9]\))[^+\-*/^].*?", serial_sm)
  42. if m:
  43. serial_sm = serial_sm.replace(m.group(1), "")
  44. serial_sm_start = serial_sm_start + 3
  45. else:
  46. m = re.search(r"[..](\([1-9]\))$", serial_sm)
  47. if m:
  48. serial_sm = serial_sm.replace(m.group(1), "")
  49. serial_sm_end = serial_sm_end - 3
  50. if len(serial_sm) > 0:
  51. if re.match(r"[,,;;::.。.??]", serial_sm[-1]):
  52. serial_sm = serial_sm[:-1]
  53. serial_sm_end = serial_sm_end - 1
  54. re_filter = True
  55. if len(serial_sm) > 0:
  56. if re.match(r"[,,;;::.。.??]", serial_sm[0]):
  57. serial_sm = serial_sm[1:]
  58. serial_sm_start = serial_sm_start + 1
  59. re_filter = True
  60. if re_filter and sm_filter(serial_sm): # 经过上面处理后,再筛选一下
  61. serial_sm = "犇" # 不能置为"",如果置为"",下面循环找serial_sm的时候,就不会继续找后面的了
  62. return sm_correct(serial_sm, serial_sm_start, serial_sm_end) # 原题目,提取的公式,公式始、终索引
  63. def sm_correct(serial_sm, serial_sm_start, serial_sm_end):
  64. """
  65. 当前提取出来的连续字符序列可能有问题,需要纠正
  66. 1.由于公式中括号不成对,导致提取一直提取到题目结束:{{t|0<=t<=26},而后者的定义域为R.不相等.因为前者的定义域为R,而后者的定义域为{x|x<>0} <-- 先不解决
  67. 2.f(x)=2^x-a*x+7(a>0或a<-1)--->这种提取连在一起,影响后面符号识别:
  68. 对2的处理思路,认为以(.*?)$结束的公式,如果括号内没有汉字,只
  69. :param serial_sm:
  70. :return: new_serial_sm,new_serial_sm_start,new_serial_sm_end
  71. """
  72. # serial_sm = serial_sm.replace("<=","<").replace(">=",">")
  73. ss = re.search(r".+[^\+\-\*/sgtfFGhHT=∈∉](\(.+?\))$",
  74. serial_sm) # <--改成贪婪匹配模式,希望前面进了能多,只匹配最后一个满足条件的括号cos(x) sin(x) abs(x) log[x](a) sqrt(x) f(x)
  75. # ss2 = re.search(r'[)\d]\((.{1,6})\)$',serial_sm) #括号前面是右括号,或是个数字,再加上括号里面含有
  76. # ?为啥第一个不能是括号,因为怕括号取过头了
  77. # if len(serial_sm)>0 and ((serial_sm[0] != "(" and ss) or (ss2)) and re.search(r"[\u4e00-\u9fa5><=,]",ss.group(1)):
  78. if len(serial_sm) > 0 and ss and re.search(r"[\u4e00-\u9fa5><=∈∉,]",
  79. ss.group(1)): # ?为啥第一个不能是括号,因为怕括号取过头了,group(1)拿到范围更大的,而不是最后一个括号的内容
  80. left_kuo = serial_sm.rfind(')(')
  81. if left_kuo == -1:
  82. left_kuo = serial_sm.rfind("(")
  83. else:
  84. left_kuo += 1
  85. if not is_double_kuohao(serial_sm[:left_kuo]):
  86. left_kuo = serial_sm[:left_kuo].rfind("(")
  87. serial_sm_end = serial_sm_end - (len(serial_sm) - left_kuo)
  88. serial_sm = serial_sm[:left_kuo]
  89. return serial_sm, serial_sm_start, serial_sm_end
  90. def sm_filter(serial_sm):
  91. """
  92. 提取出的连续字符序列,有很多情况不是公式,将不可能是公式的情况筛选出来
  93. eg:1)单字符,但非汉字,非字母,非αβγ
  94. 2)
  95. :param serial_sm:提取出的连续字符序列,待验证数学公式
  96. :return:True:不是数学公式,应该过滤掉/False:不应该过滤掉
  97. """
  98. b = False
  99. if len(serial_sm) == 1:
  100. if re.match(r"[^ραβγφδεξληθa-z\d]", serial_sm):
  101. b = True
  102. elif re.match(r"\([\u4e00-\u9fa5,,。??]+\)", serial_sm): # (删掉全部由汉字构成的带括号字符串)
  103. b = True
  104. elif len(re.findall(r"[\u4e00-\u9fa5]", serial_sm)) > 20: # (删掉全部由汉字构成的带括号字符串)
  105. b = True
  106. elif re.match(r"^\([1-5]\)$", serial_sm):
  107. b = True
  108. elif serial_sm == "img":
  109. b = True
  110. elif re.match(r"\(.+?\)", serial_sm):
  111. if re.search(r"[\u4e00-\u9fa5。??]", serial_sm[1:-1]) and \
  112. re.search(r"[^><=]", serial_sm[1:-1]): # (a是2018年的产量) <--这个上面筛不掉
  113. b = True
  114. elif re.search(r"\[[\u4e00-\u9fa5]", serial_sm) or \
  115. re.search(r"[\u4e00-\u9fa5]\(", serial_sm):
  116. b = True
  117. elif not re.search(r"[\da-zA-Z]", serial_sm): # no digit and alpha->not formula
  118. b = True
  119. return b
  120. def formula_extract_lqy(line):
  121. """
  122. 提取出句子中的公式,将对应公式用占位符#替换,提取的公式放在列表中
  123. 这步骤
  124. :param line:
  125. :param
  126. :return:line:公式用占位符#替换以后的题目,res:提取出来的公式列表
  127. """
  128. res = []
  129. line = str(line)
  130. if len(line) < 1000: # 可能有公式根本没有清洗,还是html格式
  131. line = re.sub(r"\s", "", line)
  132. line = line.replace("⑴", "①"). \
  133. replace("⑵", "②"). \
  134. replace("⑶", "③"). \
  135. replace("⑷", "④"). \
  136. replace("<=", "<").\
  137. replace("(", "(").\
  138. replace(")", ")")
  139. # 不能直接替换,用为向量中,有很多<OA>=3这样的符号
  140. line = rex.sub(r"(?<!\<[a-z]|\<[A-Z]{2})>=", ">", line)
  141. # ########否则AB//平面ABC会提取成---> AB// ABC
  142. def sub_line_plane(m):
  143. lp_dict = {"直线": "(line)",
  144. "平面": "(plane)",
  145. "底面": "(plane)",
  146. "面": "(plane)",
  147. "截面": "(plane)"}
  148. return m.group(1) + lp_dict[m.group(2)]
  149. line = re.sub(r"(//|⊂|⊥)(直线|平?面|底?面)", sub_line_plane, line)
  150. v_line = line
  151. has_serial_sm = True
  152. serial_sm_end = -1
  153. while_num = 0
  154. while has_serial_sm and while_num <= 50:
  155. while_num += 1
  156. v_line = v_line[serial_sm_end + 1:]
  157. serial_sm, serial_sm_start, serial_sm_end = find_serial_sm(v_line)
  158. if len(serial_sm) > 0:
  159. line = line.replace(serial_sm, "#", 1) # 占位
  160. if serial_sm != '犇':
  161. res.append(serial_sm)
  162. else:
  163. has_serial_sm = False
  164. # print("公式列表:{}".format(res))
  165. # return line, res
  166. return res
  167. if __name__ == "__main__":
  168. line = " 已知点O为原点,点A,B的坐标分别为(a,0)和(0,a),其中a∈(0,+∞),点P在AB上且<AP>=t<AB>(0<=t<=1),则<OA>⋅<OP>的最大值为"
  169. # line = "求下列函数的定义域: (1)y=(1/(log[3](3*x-2)));(2)y=log[a](2-x),(a>0,且a<>1);(3)y=log[a](1-x)^2,(a>0,且a<>1)"
  170. # line = "已知全集U=A∪B={x∈N|0<=x<=10} ,A∩(∁UB)={1,3,5,7} ,试求集合B ."
  171. # line = "A={(x,y)|x+y<=1,x∈N,y∈N} ,则x=0 或1 ,y=0 或1 ,所以A={(0,0),(0,1),(1,0)} ,元素的个数是3 故选C ."
  172. # line = "集合A={(x,y)|x+y<=1,x∈N,y∈N} 中元素的个数是(  )"
  173. # line = "范围是2<=x<=8.(1)则x是正整数"
  174. # line = "函数f(x)={x-2,x<2;f(x-1),x>=2} 则f(2)= (\u3000\u3000)."
  175. # line = " 二次函数y=a*x^2+b*x+c 的零点分别为-2,3 ,若x∈(-2,3) 时,f(x)<0 且f(-6)=36 ,则二次函数f(x) 的解析式为img ."
  176. # line = " 由AB=3 ,y) 则由点N是△ABC内部或边上一点可得,{0<=x<=3;0<=y<=4;4*x+3*y-12<=0} 则<BC>=(-2.x).<AM>=(α.b).|<AM>|=((12)/5) 由AM⊥BC于M可知<AM.><BC>=0<AM>|=((12)/5)| 可得b=((36)/(25)).α=((48)/(25)) 令Z=<AM.><AN>=((48*x+36*y)/(25)) ,从而转化为线性规划问题,求目标函数Z在平面区域△ABC内的最大值利用线性规划知识可得当过边界BC时将取得最大值,此时Z=((144)/(25)) 故选 A"
  177. # line = " 由题意{n*p=(5/2);n*p(1-p)=(5/4)⇒p=(1/2),n=5 ,所以P(X=1)=_^(C)p(1-p)^4=5*(1/(32))=(5/(32)) ."
  178. # # # # print(len(line))
  179. # line = "O 、A 、B 是平面上的三点"
  180. # line = "求以下两点间的距离: (1)(4,5,6) ,(-7,3,11) ; (2)(1,2,2) ,(4,6,14) ; (3((1/3),(2/3),(2/3)),(-(1/3),-(2/3),(2/3)) ; (4)((1/3),(3/4),(4/5)),((5/6),(2/3),(3/(10))) ."
  181. # line = "矩形,PA⊥ 平面ABCD ,PB 、PD 与平面ABCD 所成角的正切值依次是1 、(1/2) ,AP=2 ,E 、F 依次是PB 、PC 的中点. (1)求证:PB⊥ 平面AEFD ; (2)求直线EC 与平面PAD 所成角的正弦值."
  182. # line = "已知▵ABC 中,<AB>=<c>,<BC>=<a>,<CA>=<b> ,若<a>⋅<b>=<b>⋅<c>,<c>⋅<b>+<c>⋅<c>=0 ,则▵ABC 的形状为(  )"
  183. # line = "化简下列各式:(1)sqrt(3-2*sqrt(2))+root[3]((1-sqrt(2))^3)+root[4]((1-sqrt(2))^4);(2)sqrt(4*x^2+12*x+9)+sqrt(4*x^2-20*x+25)(-(3/2)<=x<=(5/2))."
  184. line = "根据《电动自行车通用技术条件》(GB17761)标准规定,电动自行车的最高时速应不大于20km/h,整车质量应不大于40kg,假设一成年人骑着电动自行车在平直的公路上按上述标准快速行驶时所受阻力是总重量的0.05倍,则电动车电机的输出功率最接近于(  )"
  185. print(formula_extract_lqy(line))
  186. # print(sm_correct('<AP>=t<AB>(0<=t<=1)', 0, 50))
  187. # print(find_serial_sm('a∈(0,+∞)'))
  188. # import pandas as pd
  189. # data = pd.read_excel(r"C:\Users\Administrator\Desktop\替换.xlsx")
  190. # maple_items_list = data["train"].tolist()
  191. # special_name = data["special_name"].tolist()
  192. # # maple_parse_list = data["parse"].tolist()[:20]
  193. # print("数据读取完毕......")
  194. # item_formula = []
  195. # parse_formula = []
  196. # zhanwei_items = []
  197. #
  198. # # for item,parse in tqdm(zip(maple_items_list,maple_parse_list)):
  199. # for item in tqdm(maple_items_list):
  200. # # try:
  201. # # item = re.sub(r"[==]\s*(\(\s*\)|_{1,5}|(\s*))", "等于多少", item)
  202. # # item = re.sub(r"\(\s*[??]*\s*\)|(\s*[??]*\s*)$", "", item)
  203. # # except:
  204. # # item = item
  205. # ##########题文
  206. # try:
  207. # zhanwei_item,formula_list_item = formula_extract_lqy(item)
  208. # except:
  209. # zhanwei_item = item
  210. # formula_list_item = []
  211. # item_formula.append(formula_list_item)
  212. # zhanwei_items.append(zhanwei_item)
  213. # print("【成功】-----公式提取成功待写入--------{}".format(str(formula_list_item)))
  214. # ##########解析
  215. # # try:
  216. # # zhanwei_parse,formula_list_parse = formula_extract_lqy(parse)
  217. # # except:
  218. # # zhanwei_parse = parse
  219. # # formula_list_parse = []
  220. # # parse_formula.append(formula_list_parse)
  221. # print("*****************开始公式识别*******************")
  222. # reg_formula = [list(map(math_symb_reg,ff)) for ff in item_formula]
  223. # print("*****************开始断句替换*******************")
  224. #
  225. # reg_items = []
  226. # yuanjus = []
  227. # zhanwei_duanjus = []
  228. # special_list = []
  229. #
  230. # def sub_mode(i):
  231. # res = ""
  232. # if len(reg_formula[i]) > 0:
  233. # res = reg_formula[i][0]
  234. # del reg_formula[i][0]
  235. # return "【{}】".format(res)
  236. #
  237. # for i,item in enumerate(zhanwei_items):
  238. # zhanwei_duanju = re.compile(r"[,;?,;?..]").split(str(item))
  239. # zhanwei_duanju = [str(i) for i in zhanwei_duanju if i!=""]
  240. #
  241. # reg_l = []
  242. # yuanju = [str(maple_items_list[i])]
  243. # yuanju.extend([" "]*(len(zhanwei_duanju)-1))
  244. # ss = [special_name[i]] * len(zhanwei_duanju)
  245. #
  246. # for zd in zhanwei_duanju:
  247. # reg_item = re.sub(r"#", sub_mode(i), zd)
  248. # reg_l.append(reg_item)
  249. # if len(yuanju) != len(reg_l):
  250. # yuanju.append([" "]*20)
  251. # yuanju = yuanju[:len(reg_l)]
  252. # # print("原句列表为:{}".format(yuanju))
  253. # # print("占位短句列表为:{}".format(zhanwei_duanju))
  254. # # print("公式类别列表为:{}".format(reg_l))
  255. # reg_items.extend(reg_l)
  256. # zhanwei_duanjus.extend(zhanwei_duanju)
  257. # yuanjus.extend(yuanju)
  258. # special_list.extend(ss)
  259. # # data["item_formula"] = item_formula
  260. # # data["parse_formula"] = parse_formula
  261. # # data["reg_items"] = reg_items
  262. # # data.to_excel("lqy_formula_extraction.xlsx")
  263. # print(len(yuanjus))
  264. # print(len(reg_items))
  265. # print(len(zhanwei_duanjus))
  266. # print(len(special_list))
  267. # pd.DataFrame({"原句": yuanjus, "公式识别": reg_items, "占位": zhanwei_duanjus,"special":special_list}).to_excel("all_duanju_50_5000.xlsx")
  268. # pd.DataFrame({"原句":maple_items_list,"公式识别":reg_formula,"原公式":item_formula,"占位":zhanwei_duanjus,"special":special_list}).to_excel("all_duanju_reg.xlsx")