htmlparser.py 55 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144
  1. #coding:utf8
  2. import re
  3. from BaseDataMaintenance.maintenance.product.productUtils import is_similar
  4. import logging
  5. logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
  6. logger = logging.getLogger(__name__)
  7. logger.setLevel(logging.INFO)
  8. from bs4 import BeautifulSoup
  9. import copy
  10. end_pattern = "商务要求|评分标准|商务条件|商务条件"
  11. _param_pattern = "(产品|技术|清单|配置|参数|具体|明细|项目|招标|货物|服务|规格|工作|具体)[及和与]?(指标|配置|条件|要求|参数|需求|规格|条款|名称及要求)|配置清单|(质量|技术).{,10}要求|验收标准|^(参数|功能)$"
  12. meter_pattern = "[><≤≥±]\d+|\d+(?:[μucmkK微毫千]?[米升LlgGmMΩ]|摄氏度|英寸|度|天|VA|dB|bpm|rpm|kPa|mol|cmH20|%|°|Mpa|Hz|K?HZ|℃|W|min|[*×xX])|[*×xX]\d+|/min|\ds[^a-zA-Z]|GB.{,20}标准|PVC|PP|角度|容积|色彩|自动|流量|外径|轴位|折射率|帧率|柱镜|振幅|磁场|镜片|防漏|强度|允差|心率|倍数|瞳距|底座|色泽|噪音|间距|材质|材料|表面|频率|阻抗|浓度|兼容|防尘|防水|内径|实时|一次性|误差|性能|距离|精确|温度|超温|范围|跟踪|对比度|亮度|[横纵]向|均压|负压|正压|可调|设定值|功能|检测|高度|厚度|宽度|深度|[单双多]通道|效果|指数|模式|尺寸|重量|峰值|谷值|容量|寿命|稳定性|高温|信号|电源|电流|转换率|效率|释放量|转速|离心力|向心力|弯曲|电压|功率|气量|国标|标准协议|灵敏度|最大值|最小值|耐磨|波形|高压|性强|工艺|光源|低压|压力|压强|速度|湿度|重量|毛重|[MLX大中小]+码|净重|颜色|[红橙黄绿青蓝紫]色|不锈钢|输入|输出|噪声|认证|配置"
  13. not_meter_pattern = "投标报价|中标金额|商务部分|公章|分值构成|业绩|详见|联系人|联系电话|合同价|金额|采购预算|资金来源|费用|质疑|评审因素|评审标准|商务资信|商务评分|专家论证意见|评标方法|代理服务费|售后服务|评分类型|评分项目|预算金额|得\d+分|项目金额|详见招标文件|乙方"
  14. def getTrs(tbody):
  15. #获取所有的tr
  16. trs = []
  17. if tbody.name=="table":
  18. body = tbody.find("tbody",recursive=False)
  19. if body is not None:
  20. tbody = body
  21. objs = tbody.find_all(recursive=False)
  22. for obj in objs:
  23. if obj.name=="tr":
  24. trs.append(obj)
  25. if obj.name=="tbody" or obj.name=="table":
  26. for tr in obj.find_all("tr",recursive=False):
  27. trs.append(tr)
  28. return trs
  29. def fixSpan(tbody):
  30. # 处理colspan, rowspan信息补全问题
  31. #trs = tbody.findChildren('tr', recursive=False)
  32. trs = getTrs(tbody)
  33. ths_len = 0
  34. ths = list()
  35. trs_set = set()
  36. #修改为先进行列补全再进行行补全,否则可能会出现表格解析混乱
  37. # 遍历每一个tr
  38. for indtr, tr in enumerate(trs):
  39. ths_tmp = tr.findChildren('th', recursive=False)
  40. #不补全含有表格的tr
  41. if len(tr.findChildren('table'))>0:
  42. continue
  43. if len(ths_tmp) > 0:
  44. ths_len = ths_len + len(ths_tmp)
  45. for th in ths_tmp:
  46. ths.append(th)
  47. trs_set.add(tr)
  48. # 遍历每行中的element
  49. tds = tr.findChildren(recursive=False)
  50. for indtd, td in enumerate(tds):
  51. # 若有colspan 则补全同一行下一个位置
  52. if 'colspan' in td.attrs:
  53. if str(re.sub("[^0-9]","",str(td['colspan'])))!="":
  54. col = int(re.sub("[^0-9]","",str(td['colspan'])))
  55. if col<100 and len(td.get_text())<1000:
  56. td['colspan'] = 1
  57. for i in range(1, col, 1):
  58. td.insert_after(copy.copy(td))
  59. for indtr, tr in enumerate(trs):
  60. ths_tmp = tr.findChildren('th', recursive=False)
  61. #不补全含有表格的tr
  62. if len(tr.findChildren('table'))>0:
  63. continue
  64. if len(ths_tmp) > 0:
  65. ths_len = ths_len + len(ths_tmp)
  66. for th in ths_tmp:
  67. ths.append(th)
  68. trs_set.add(tr)
  69. # 遍历每行中的element
  70. tds = tr.findChildren(recursive=False)
  71. for indtd, td in enumerate(tds):
  72. # 若有rowspan 则补全下一行同样位置
  73. if 'rowspan' in td.attrs:
  74. if str(re.sub("[^0-9]","",str(td['rowspan'])))!="":
  75. row = int(re.sub("[^0-9]","",str(td['rowspan'])))
  76. td['rowspan'] = 1
  77. for i in range(1, row, 1):
  78. # 获取下一行的所有td, 在对应的位置插入
  79. if indtr+i<len(trs):
  80. tds1 = trs[indtr + i].findChildren(['td','th'], recursive=False)
  81. if len(tds1) >= (indtd) and len(tds1)>0:
  82. if indtd > 0:
  83. tds1[indtd - 1].insert_after(copy.copy(td))
  84. else:
  85. tds1[0].insert_before(copy.copy(td))
  86. elif indtd-2>0 and len(tds1) > 0 and len(tds1) == indtd - 1: # 修正某些表格最后一列没补全
  87. tds1[indtd-2].insert_after(copy.copy(td))
  88. def getTable(tbody):
  89. #trs = tbody.findChildren('tr', recursive=False)
  90. fixSpan(tbody)
  91. trs = getTrs(tbody)
  92. inner_table = []
  93. for tr in trs:
  94. tr_line = []
  95. tds = tr.findChildren(['td','th'], recursive=False)
  96. if len(tds)==0:
  97. tr_line.append([re.sub('\xa0','',tr.get_text()),0]) # 2021/12/21 修复部分表格没有td 造成数据丢失
  98. for td in tds:
  99. tr_line.append([re.sub('\xa0','',td.get_text()),0])
  100. #tr_line.append([td.get_text(),0])
  101. inner_table.append(tr_line)
  102. return inner_table
  103. class ParseDocument():
  104. def __init__(self,_html,auto_merge_table=True):
  105. if _html is None:
  106. _html = ""
  107. self.html = _html
  108. # self.soup = BeautifulSoup(self.html,"lxml")
  109. # self.soup = BeautifulSoup(self.html,"html.parser")
  110. self.auto_merge_table = auto_merge_table
  111. self.soup = BeautifulSoup(self.html,"html5lib")
  112. _body = self.soup.find("body")
  113. if _body is not None:
  114. self.soup = _body
  115. self.list_obj = self.get_soup_objs(self.soup)
  116. # for obj in self.list_obj:
  117. # print("obj",obj.get_text()[:20])
  118. self.tree = self.buildParsetree(self.list_obj,[],auto_merge_table)
  119. # #识别目录树
  120. # if self.parseTree:
  121. # self.parseTree.printParseTree()
  122. # self.print_tree(self.tree,"-|")
  123. def get_soup_objs(self,soup,list_obj=None):
  124. if list_obj is None:
  125. list_obj = []
  126. childs = soup.find_all(recursive=False)
  127. for _obj in childs:
  128. childs1 = _obj.find_all(recursive=False)
  129. if len(childs1)==0 or len(_obj.get_text())<40 or _obj.name=="table":
  130. list_obj.append(_obj)
  131. else:
  132. self.get_soup_objs(_obj,list_obj)
  133. return list_obj
  134. def fix_tree(self,_product):
  135. products = extract_products(self.tree,_product)
  136. if len(products)>0:
  137. self.tree = self.buildParsetree(self.list_obj,products,self.auto_merge_table)
  138. def print_tree(self,tree,append=""):
  139. self.set_tree_id = set()
  140. if append=="":
  141. for t in tree:
  142. logger.debug("%s text:%s title:%s title_text:%s before:%s after%s product:%s"%("==>",t["text"][:50],t["sentence_title"],t["sentence_title_text"],t["title_before"],t["title_after"],t["has_product"]))
  143. for t in tree:
  144. _id = id(t)
  145. if _id in self.set_tree_id:
  146. continue
  147. self.set_tree_id.add(_id)
  148. logger.info("%s text:%s title:%s title_text:%s before:%s after%s product:%s"%(append,t["text"][:50],t["sentence_title"],t["sentence_title_text"],t["title_before"],t["title_after"],t["has_product"]))
  149. childs = t["child_title"]
  150. self.print_tree(childs,append=append+"-|")
  151. def is_title_first(self,title):
  152. if title in ("一","1","Ⅰ","a","A"):
  153. return True
  154. return False
  155. def find_title_by_pattern(self,_text,_pattern="(^|★|▲|:|:|\s+)(?P<title_1>(?P<title_1_index_0_0>第?)(?P<title_1_index_1_1>[一二三四五六七八九十ⅠⅡⅢⅣⅤⅥⅦⅧⅨⅩⅪⅫ]+)(?P<title_1_index_2_0>[、章册包标部.::、、]+))|" \
  156. "([\s★▲\*]*)(?P<title_3>(?P<title_3_index_0_0>[^一二三四五六七八九十\dⅠⅡⅢⅣⅤⅥⅦⅧⅨⅩⅪⅫ]{,3}?)(?P<title_3_index_0_1>[ⅠⅡⅢⅣⅤⅥⅦⅧⅨⅩⅪⅫ]+)(?P<title_3_index_0_2>[、章册包标部.::、、]+))|" \
  157. "([\s★▲\*]*)(?P<title_4>(?P<title_4_index_0_0>[^一二三四五六七八九十\dⅠⅡⅢⅣⅤⅥⅦⅧⅨⅩⅪⅫ]{,3}?第?)(?P<title_4_index_1_1>[一二三四五六七八九十]+)(?P<title_4_index_2_0>[节章册部\.::、、]+))|" \
  158. "([\s★▲\*]*)(?P<title_5>(?P<title_5_index_0_0>^)(?P<title_5_index_1_1>[一二三四五六七八九十]+)(?P<title_5_index_2_0>)[^一二三四五六七八九十节章册部\.::、、])|" \
  159. "([\s★▲\*]*)(?P<title_12>(?P<title_12_index_0_0>[^一二三四五六七八九十\dⅠⅡⅢⅣⅤⅥⅦⅧⅨⅩⅪⅫ]{,3}?\d{1,2}[\..、\s\-]\d{1,2}[\..、\s\-]\d{1,2}[\..、\s\-]\d{1,2}[\..、\s\-])(?P<title_12_index_1_1>\d{1,2})(?P<title_12_index_2_0>[\..、\s\-]?))|"\
  160. "([\s★▲\*]*)(?P<title_11>(?P<title_11_index_0_0>[^一二三四五六七八九十\dⅠⅡⅢⅣⅤⅥⅦⅧⅨⅩⅪⅫ]{,3}?\d{1,2}[\..、\s\-]\d{1,2}[\..、\s\-]\d{1,2}[\..、\s\-])(?P<title_11_index_1_1>\d{1,2})(?P<title_11_index_2_0>[\..、\s\-]?))|" \
  161. "([\s★▲\*]*)(?P<title_10>(?P<title_10_index_0_0>[^一二三四五六七八九十\dⅠⅡⅢⅣⅤⅥⅦⅧⅨⅩⅪⅫ]{,3}?\d{1,2}[\..、\s\-]\d{1,2}[\..、\s\-])(?P<title_10_index_1_1>\d{1,2})(?P<title_10_index_2_0>[\..、\s\-]?))|" \
  162. "([\s★▲\*]*)(?P<title_7>(?P<title_7_index_0_0>[^一二三四五六七八九十\dⅠⅡⅢⅣⅤⅥⅦⅧⅨⅩⅪⅫ]{,3}?\d{1,2}[\..\s\-])(?P<title_7_index_1_1>\d{1,2})(?P<title_7_index_2_0>[\..包标::、\s\-]*))|" \
  163. "(^[\s★▲\*]*)(?P<title_6>(?P<title_6_index_0_0>[^一二三四五六七八九十\dⅠⅡⅢⅣⅤⅥⅦⅧⅨⅩⅪⅫ]{,3}?包?)(?P<title_6_index_0_1>\d{1,2})(?P<title_6_index_2_0>[\..、\s\-包标]*))|" \
  164. "([\s★▲\*]*)(?P<title_15>(?P<title_15_index_0_0>[^一二三四五六七八九十\dⅠⅡⅢⅣⅤⅥⅦⅧⅨⅩⅪⅫ]{,3}?[((]?)(?P<title_15_index_1_1>\d{1,2})(?P<title_15_index_2_0>[))包标\..::、]+))|" \
  165. "([\s★▲\*]*)(?P<title_17>(?P<title_17_index_0_0>[^一二三四五六七八九十\dⅠⅡⅢⅣⅤⅥⅦⅧⅨⅩⅪⅫ]{,3}?[((]?)(?P<title_17_index_1_1>[a-zA-Z]+)(?P<title_17_index_2_0>[))包标\..::、]+))|" \
  166. "([\s★▲\*]*)(?P<title_19>(?P<title_19_index_0_0>[^一二三四五六七八九十\dⅠⅡⅢⅣⅤⅥⅦⅧⅨⅩⅪⅫ]{,3}?[((]?)(?P<title_19_index_1_1>[一二三四五六七八九十ⅠⅡⅢⅣⅤⅥⅦⅧⅨⅩⅪⅫ]+)(?P<title_19_index_2_0>[))]))"
  167. ):
  168. _se = re.search(_pattern,_text)
  169. groups = []
  170. if _se is not None:
  171. _gd = _se.groupdict()
  172. for k,v in _gd.items():
  173. if v is not None:
  174. groups.append((k,v))
  175. if len(groups):
  176. # groups.sort(key=lambda x:x[0])
  177. return groups
  178. return None
  179. def make_increase(self,_sort,_title,_add=1):
  180. if len(_title)==0 and _add==0:
  181. return ""
  182. if len(_title)==0 and _add==1:
  183. return _sort[0]
  184. _index = _sort.index(_title[-1])
  185. next_index = (_index+_add)%len(_sort)
  186. next_chr = _sort[next_index]
  187. if _index==len(_sort)-1:
  188. _add = 1
  189. else:
  190. _add = 0
  191. return next_chr+self.make_increase(_sort,_title[:-1],_add)
  192. def get_next_title(self,_title):
  193. if re.search("^\d+$",_title) is not None:
  194. return str(int(_title)+1)
  195. if re.search("^[一二三四五六七八九十百]+$",_title) is not None:
  196. if _title[-1]=="十":
  197. return _title+"一"
  198. if _title[-1]=="百":
  199. return _title+"零一"
  200. if _title[-1]=="九":
  201. if len(_title)==1:
  202. return "十"
  203. if len(_title)==2:
  204. if _title[0]=="十":
  205. return "二十"
  206. if len(_title)==3:
  207. if _title[0]=="九":
  208. return "一百"
  209. else:
  210. _next_title = self.make_increase(['一','二','三','四','五','六','七','八','九','十'],re.sub("[十百]",'',_title[0]))
  211. return _next_title+"十"
  212. _next_title = self.make_increase(['一','二','三','四','五','六','七','八','九','十'],re.sub("[十百]",'',_title))
  213. _next_title = list(_next_title)
  214. _next_title.reverse()
  215. if _next_title[-1]!="十":
  216. if len(_next_title)>=2:
  217. _next_title.insert(-1,'十')
  218. if len(_next_title)>=4:
  219. _next_title.insert(-3,'百')
  220. if _title[0]=="十":
  221. if _next_title=="十":
  222. _next_title = ["二","十"]
  223. _next_title.insert(0,"十")
  224. _next_title = "".join(_next_title)
  225. return _next_title
  226. if re.search("^[a-z]+$",_title) is not None:
  227. _next_title = self.make_increase([chr(i+ord('a')) for i in range(26)],_title)
  228. _next_title = list(_next_title)
  229. _next_title.reverse()
  230. return "".join(_next_title)
  231. if re.search("^[A-Z]+$",_title) is not None:
  232. _next_title = self.make_increase([chr(i+ord('A')) for i in range(26)],_title)
  233. _next_title = list(_next_title)
  234. _next_title.reverse()
  235. return "".join(_next_title)
  236. if re.search("^[ⅠⅡⅢⅣⅤⅥⅦⅧⅨⅩⅪⅫ]$",_title) is not None:
  237. _sort = ["Ⅰ","Ⅱ","Ⅲ","Ⅳ","Ⅴ","Ⅵ","Ⅶ","Ⅷ","Ⅸ","Ⅹ","Ⅺ","Ⅻ"]
  238. _index = _sort.index(_title)
  239. if _index<len(_sort)-1:
  240. return _sort[_index+1]
  241. return None
  242. def count_title_before(self,list_obj):
  243. dict_before = {}
  244. dict_sentence_count = {}
  245. illegal_sentence = set()
  246. for obj_i in range(len(list_obj)):
  247. obj = list_obj[obj_i]
  248. _type = "sentence"
  249. _text = obj.text.strip()
  250. if obj.name=="table":
  251. _type = "table"
  252. _text = str(obj)
  253. _append = False
  254. if _type=="sentence":
  255. if len(_text)>10 and len(_text)<100:
  256. if _text not in dict_sentence_count:
  257. dict_sentence_count[_text] = 0
  258. dict_sentence_count[_text] += 1
  259. if re.search("\d+页",_text) is not None:
  260. illegal_sentence.add(_text)
  261. elif len(_text)<10:
  262. if re.search("第\d+页",_text) is not None:
  263. illegal_sentence.add(_text)
  264. sentence_groups = self.find_title_by_pattern(_text[:10])
  265. if sentence_groups:
  266. # c062f53cf83401e671822003d63c1828print("sentence_groups",sentence_groups)
  267. sentence_title = sentence_groups[0][0]
  268. sentence_title_text = sentence_groups[0][1]
  269. title_index = sentence_groups[-2][1]
  270. title_before = sentence_groups[1][1].replace("(","(").replace(":",":").replace(":",";").replace(",",".").replace(",",".").replace("、",".")
  271. title_after = sentence_groups[-1][1].replace(")",")").replace(":",":").replace(":",";").replace(",",".").replace(",",".").replace("、",".")
  272. next_index = self.get_next_title(title_index)
  273. if title_before not in dict_before:
  274. dict_before[title_before] = 0
  275. dict_before[title_before] += 1
  276. for k,v in dict_sentence_count.items():
  277. if v>10:
  278. illegal_sentence.add(k)
  279. return dict_before,illegal_sentence
  280. def is_page_no(self,sentence):
  281. if len(sentence)<10:
  282. if re.search("\d+页|^\-\d+\-$",sentence) is not None:
  283. return True
  284. def block_tree(self,childs):
  285. for child in childs:
  286. if not child["block"]:
  287. child["block"] = True
  288. childs2 = child["child_title"]
  289. self.block_tree(childs2)
  290. def buildParsetree(self,list_obj,products=[],auto_merge_table=True):
  291. self.parseTree = None
  292. trees = []
  293. list_length = []
  294. for obj in list_obj[:200]:
  295. if obj.name!="table":
  296. list_length.append(len(obj.get_text()))
  297. if len(list_length)>0:
  298. max_length = max(list_length)
  299. else:
  300. max_length = 40
  301. max_length = min(max_length,40)
  302. logger.debug("%s:%d"%("max_length",max_length))
  303. list_data = []
  304. last_table_index = None
  305. last_table_columns = None
  306. last_table = None
  307. dict_before,illegal_sentence = self.count_title_before(list_obj)
  308. for obj_i in range(len(list_obj)):
  309. obj = list_obj[obj_i]
  310. # logger.debug("==obj %s"%obj.text[:20])
  311. _type = "sentence"
  312. _text = standard_product(obj.text)
  313. if obj.name=="table":
  314. _type = "table"
  315. _text = standard_product(str(obj))
  316. _append = False
  317. sentence_title = None
  318. sentence_title_text = None
  319. sentence_groups = None
  320. title_index = None
  321. next_index = None
  322. parent_title = None
  323. title_before = None
  324. title_after = None
  325. title_next = None
  326. childs = []
  327. list_table = None
  328. block = False
  329. has_product = False
  330. if _type=="sentence":
  331. if _text in illegal_sentence:
  332. continue
  333. sentence_groups = self.find_title_by_pattern(_text[:10])
  334. if sentence_groups:
  335. title_before = standard_title_context(sentence_groups[1][1])
  336. title_after = sentence_groups[-1][1]
  337. sentence_title_text = sentence_groups[0][1]
  338. other_text = _text.replace(sentence_title_text,"")
  339. if (title_before in dict_before and dict_before[title_before]>1) or title_after!="":
  340. sentence_title = sentence_groups[0][0]
  341. title_index = sentence_groups[-2][1]
  342. next_index = self.get_next_title(title_index)
  343. other_text = _text.replace(sentence_title_text,"")
  344. for p in products:
  345. if other_text.strip()==p.strip():
  346. has_product = True
  347. else:
  348. _fix = False
  349. for p in products:
  350. if other_text.strip()==p.strip():
  351. title_before = "=产品"
  352. sentence_title = "title_0"
  353. sentence_title_text = p
  354. title_index = "0"
  355. title_after = "产品="
  356. next_index = "0"
  357. _fix = True
  358. has_product = True
  359. break
  360. if not _fix:
  361. title_before = None
  362. title_after = None
  363. sentence_title_text = None
  364. else:
  365. if len(_text)<40 and re.search(_param_pattern,_text) is not None:
  366. for p in products:
  367. if _text.find(p)>=0:
  368. title_before = "=产品"
  369. sentence_title = "title_0"
  370. sentence_title_text = p
  371. title_index = "0"
  372. title_after = "产品="
  373. next_index = "0"
  374. _fix = True
  375. has_product = True
  376. break
  377. if _type=="sentence":
  378. if sentence_title is None and len(list_data)>0 and list_data[-1]["sentence_title"] is not None and list_data[-1]["line_width"]>=max_length*0.6:
  379. list_data[-1]["text"] += _text
  380. list_data[-1]["line_width"] = len(_text)
  381. _append = True
  382. elif sentence_title is None and len(list_data)>0 and _type==list_data[-1]["type"]:
  383. if list_data[-1]["line_width"]>=max_length*0.7:
  384. list_data[-1]["text"] += _text
  385. list_data[-1]["line_width"] = len(_text)
  386. _append = True
  387. if _type=="table":
  388. _soup = BeautifulSoup(_text,"lxml")
  389. _table = _soup.find("table")
  390. if _table is not None:
  391. list_table = getTable(_table)
  392. if len(list_table)==0:
  393. continue
  394. table_columns = len(list_table[0])
  395. if auto_merge_table:
  396. if last_table_index is not None and abs(obj_i-last_table_index)<=2 and last_table_columns is not None and last_table_columns==table_columns:
  397. if last_table is not None:
  398. trs = getTrs(_table)
  399. last_tbody = BeautifulSoup(last_table["text"],"lxml")
  400. _table = last_tbody.find("table")
  401. last_trs = getTrs(_table)
  402. _append = True
  403. for _line in list_table:
  404. last_table["list_table"].append(_line)
  405. if len(last_trs)>0:
  406. for _tr in trs:
  407. last_trs[-1].insert_after(copy.copy(_tr))
  408. last_table["text"] = re.sub("</?html>|</?body>","",str(last_tbody))
  409. last_table_index = obj_i
  410. last_table_columns = len(list_table[-1])
  411. if not _append:
  412. _data = {"type":_type, "text":_text,"list_table":list_table,"line_width":len(_text),"sentence_title":sentence_title,"title_index":title_index,
  413. "sentence_title_text":sentence_title_text,"sentence_groups":sentence_groups,"parent_title":parent_title,
  414. "child_title":childs,"title_before":title_before,"title_after":title_after,"title_next":title_next,"next_index":next_index,
  415. "block":block,"has_product":has_product}
  416. if _type=="table":
  417. last_table = _data
  418. last_table_index = obj_i
  419. if list_table:
  420. last_table_columns = last_table_columns = len(list_table[-1])
  421. if sentence_title is not None:
  422. if len(list_data)>0:
  423. if self.is_title_first(title_index):
  424. for i in range(1,len(list_data)+1):
  425. _d = list_data[-i]
  426. if _d["sentence_title"] is not None:
  427. _data["parent_title"] = _d
  428. _d["child_title"].append(_data)
  429. break
  430. else:
  431. _find = False
  432. for i in range(1,len(list_data)+1):
  433. if _find:
  434. break
  435. _d = list_data[-i]
  436. if _d.get("sentence_title")==sentence_title and title_before==_d["title_before"] and title_after==_d["title_after"]:
  437. if _d["next_index"]==title_index and _d["title_next"] is None and not _d["block"]:
  438. _data["parent_title"] = _d["parent_title"]
  439. _d["title_next"] = _data
  440. if len(_d["child_title"])>0:
  441. _d["child_title"][-1]["title_next"] = ""
  442. self.block_tree(_d["child_title"])
  443. if _d["parent_title"] is not None:
  444. _d["parent_title"]["child_title"].append(_data)
  445. _find = True
  446. break
  447. for i in range(1,len(list_data)+1):
  448. if _find:
  449. break
  450. _d = list_data[-i]
  451. if i==1 and not _d["block"] and _d.get("sentence_title")==sentence_title and title_before==_d["title_before"] and title_after==_d["title_after"]:
  452. _data["parent_title"] = _d["parent_title"]
  453. _d["title_next"] = _data
  454. if len(_d["child_title"])>0:
  455. _d["child_title"][-1]["title_next"] = ""
  456. self.block_tree(_d["child_title"])
  457. if _d["parent_title"] is not None:
  458. _d["parent_title"]["child_title"].append(_data)
  459. _find = True
  460. break
  461. title_before = standard_title_context(title_before)
  462. title_after = standard_title_context(title_after)
  463. for i in range(1,len(list_data)+1):
  464. if _find:
  465. break
  466. _d = list_data[-i]
  467. if _d.get("sentence_title")==sentence_title and title_before==standard_title_context(_d["title_before"]) and title_after==standard_title_context(_d["title_after"]):
  468. if _d["next_index"]==title_index and _d["title_next"] is None and not _d["block"]:
  469. _data["parent_title"] = _d["parent_title"]
  470. _d["title_next"] = _data
  471. if len(_d["child_title"])>0:
  472. _d["child_title"][-1]["title_next"] = ""
  473. self.block_tree(_d["child_title"])
  474. if _d["parent_title"] is not None:
  475. _d["parent_title"]["child_title"].append(_data)
  476. _find = True
  477. break
  478. for i in range(1,len(list_data)+1):
  479. if _find:
  480. break
  481. _d = list_data[-i]
  482. if not _d["block"] and _d.get("sentence_title")==sentence_title and title_before==standard_title_context(_d["title_before"]) and title_after==standard_title_context(_d["title_after"]):
  483. _data["parent_title"] = _d["parent_title"]
  484. _d["title_next"] = _data
  485. if len(_d["child_title"])>0:
  486. _d["child_title"][-1]["title_next"] = ""
  487. # self.block_tree(_d["child_title"])
  488. if _d["parent_title"] is not None:
  489. _d["parent_title"]["child_title"].append(_data)
  490. _find = True
  491. break
  492. for i in range(1,min(len(list_data)+1,20)):
  493. if _find:
  494. break
  495. _d = list_data[-i]
  496. if not _d["block"] and _d.get("sentence_title")==sentence_title and title_before==standard_title_context(_d["title_before"]):
  497. _data["parent_title"] = _d["parent_title"]
  498. _d["title_next"] = _data
  499. if len(_d["child_title"])>0:
  500. _d["child_title"][-1]["title_next"] = ""
  501. # self.block_tree(_d["child_title"])
  502. if _d["parent_title"] is not None:
  503. _d["parent_title"]["child_title"].append(_data)
  504. _find = True
  505. break
  506. if not _find:
  507. if len(list_data)>0:
  508. for i in range(1,len(list_data)+1):
  509. _d = list_data[-i]
  510. if _d.get("sentence_title") is not None:
  511. _data["parent_title"] = _d
  512. _d["child_title"].append(_data)
  513. break
  514. else:
  515. if len(list_data)>0:
  516. for i in range(1,len(list_data)+1):
  517. _d = list_data[-i]
  518. if _d.get("sentence_title") is not None:
  519. _data["parent_title"] = _d
  520. _d["child_title"].append(_data)
  521. break
  522. list_data.append(_data)
  523. for _data in list_data:
  524. childs = _data["child_title"]
  525. for c_i in range(len(childs)):
  526. cdata = childs[c_i]
  527. if cdata["has_product"]:
  528. continue
  529. else:
  530. if c_i>0:
  531. last_cdata = childs[c_i-1]
  532. if cdata["sentence_title"] is not None and last_cdata["sentence_title"] is not None and last_cdata["title_before"]==cdata["title_before"] and last_cdata["title_after"]==cdata["title_after"] and last_cdata["has_product"]:
  533. cdata["has_product"] = True
  534. if c_i<len(childs)-1:
  535. last_cdata = childs[c_i+1]
  536. if cdata["sentence_title"] is not None and last_cdata["sentence_title"] is not None and last_cdata["title_before"]==cdata["title_before"] and last_cdata["title_after"]==cdata["title_after"] and last_cdata["has_product"]:
  537. cdata["has_product"] = True
  538. for c_i in range(len(childs)):
  539. cdata = childs[len(childs)-1-c_i]
  540. if cdata["has_product"]:
  541. continue
  542. else:
  543. if c_i>0:
  544. last_cdata = childs[c_i-1]
  545. if cdata["sentence_title"] is not None and last_cdata["sentence_title"] is not None and last_cdata["title_before"]==cdata["title_before"] and last_cdata["title_after"]==cdata["title_after"] and last_cdata["has_product"]:
  546. cdata["has_product"] = True
  547. if c_i<len(childs)-1:
  548. last_cdata = childs[c_i+1]
  549. if cdata["sentence_title"] is not None and last_cdata["sentence_title"] is not None and last_cdata["title_before"]==cdata["title_before"] and last_cdata["title_after"]==cdata["title_after"] and last_cdata["has_product"]:
  550. cdata["has_product"] = True
  551. return list_data
  552. def standard_title_context(_title_context):
  553. return _title_context.replace("(","(").replace(")",")").replace(":",":").replace(":",";").replace(",",".").replace(",",".").replace("、",".").replace(".",".")
  554. def standard_product(sentence):
  555. return sentence.replace("(","(").replace(")",")")
  556. def extract_products(list_data,_product,_param_pattern = "产品名称|设备材料|采购内存|标的名称|采购内容|(标的|维修|系统|报价构成|商品|产品|物料|物资|货物|设备|采购品|采购条目|物品|材料|印刷品?|采购|物装|配件|资产|耗材|清单|器材|仪器|器械|备件|拍卖物|标的物|物件|药品|药材|药械|货品|食品|食材|品目|^品名|气体|标项|分项|项目|计划|包组|标段|[分子]?包|子目|服务|招标|中标|成交|工程|招标内容)[\))的]?([、\w]{,4}名称|内容|描述)|标的|标项|项目$|商品|产品|物料|物资|货物|设备|采购品|采购条目|物品|材料|印刷品|物装|配件|资产|招标内容|耗材|清单|器材|仪器|器械|备件|拍卖物|标的物|物件|药品|药材|药械|货品|食品|食材|菜名|^品目$|^品名$|^名称|^内容$"):
  557. _product = standard_product(_product)
  558. list_result = []
  559. list_table_products = []
  560. for _data_i in range(len(list_data)):
  561. _data = list_data[_data_i]
  562. _type = _data["type"]
  563. _text = _data["text"]
  564. if _type=="table":
  565. list_table = _data["list_table"]
  566. if list_table is None:
  567. continue
  568. _check = True
  569. max_length = max([len(a) for a in list_table])
  570. min_length = min([len(a) for a in list_table])
  571. if min_length<max_length/2:
  572. continue
  573. list_head_index = []
  574. _begin_index = 0
  575. head_cell_text = ""
  576. for line_i in range(len(list_table[:2])):
  577. line = list_table[line_i]
  578. line_text = ",".join([cell[0] for cell in line])
  579. for cell_i in range(len(line)):
  580. cell = line[cell_i]
  581. cell_text = cell[0]
  582. if len(cell_text)<10 and re.search(_param_pattern,cell_text) is not None and re.search("单价|数量|预算|限价|总价|品牌|规格|型号|用途|要求|采购量",line_text) is not None:
  583. _begin_index = line_i+1
  584. list_head_index.append(cell_i)
  585. for line_i in range(len(list_table)):
  586. line = list_table[line_i]
  587. for cell_i in list_head_index:
  588. if cell_i>=len(line):
  589. continue
  590. cell = line[cell_i]
  591. cell_text = cell[0]
  592. head_cell_text += cell_text
  593. # print("===head_cell_text",head_cell_text)
  594. if re.search("招标人|采购人|项目编号|项目名称|金额|^\d+$",head_cell_text) is not None:
  595. list_head_index = []
  596. for line in list_table:
  597. line_text = ",".join([cell[0] for cell in line])
  598. for cell_i in range(len(line)):
  599. cell = line[cell_i]
  600. cell_text = cell[0]
  601. if cell_text is not None and _product is not None and len(cell_text)<len(_product)*10 and cell_text.find(_product)>=0 and re.search("单价|数量|总价|规格|品牌|型号|用途|要求|采购量",line_text) is not None:
  602. list_head_index.append(cell_i)
  603. list_head_index = list(set(list_head_index))
  604. if len(list_head_index)>0:
  605. has_number = False
  606. for cell_i in list_head_index:
  607. table_products = []
  608. for line_i in range(_begin_index,len(list_table)):
  609. line = list_table[line_i]
  610. for _i in range(len(line)):
  611. cell = line[_i]
  612. cell_text = cell[0]
  613. if re.search("^\d+$",cell_text) is not None:
  614. has_number = True
  615. if cell_i>=len(line):
  616. continue
  617. cell = line[cell_i]
  618. cell_text = cell[0]
  619. if re.search(_param_pattern,cell_text) is None or has_number:
  620. if re.search("^[\da-zA-Z]+$",cell_text) is None:
  621. table_products.append(cell_text)
  622. if len(table_products)>0:
  623. logger.debug("table products %s"%(str(table_products)))
  624. if min([len(x) for x in table_products])>0 and max([len(x) for x in table_products])<=30:
  625. if re.search("招标人|代理人|预算|数量|交货期|品牌|产地","".join(table_products)) is None:
  626. list_table_products.append(table_products)
  627. _find = False
  628. for table_products in list_table_products:
  629. for _p in table_products:
  630. if is_similar(_product,_p,90):
  631. _find = True
  632. logger.debug("similar table_products %s"%(str(table_products)))
  633. list_result = list(set([a for a in table_products if len(a)>1 and len(a)<20 and re.search("费用|预算|合计|金额|万元|运费|^其他$",a) is None]))
  634. break
  635. if not _find:
  636. for table_products in list_table_products:
  637. list_result.extend(table_products)
  638. list_result = list(set([a for a in list_result if len(a)>1 and len(a)<30 and re.search("费用|预算|合计|金额|万元|运费",a) is None]))
  639. return list_result
  640. def get_childs(childs):
  641. list_data = []
  642. for _child in childs:
  643. list_data.append(_child)
  644. childs2 = _child.get("child_title",[])
  645. if len(childs2)>0:
  646. for _child2 in childs2:
  647. list_data.extend(get_childs([_child2]))
  648. return list_data
  649. def get_range_data_by_childs(list_data,childs):
  650. range_data = []
  651. list_child = get_childs(childs)
  652. list_index = []
  653. set_child = set([id(x) for x in list_child])
  654. for _data_i in range(len(list_data)):
  655. _data = list_data[_data_i]
  656. _id = id(_data)
  657. if _id in set_child:
  658. list_index.append(_data_i)
  659. if len(list_index)>0:
  660. range_data = list_data[min(list_index):max(list_index)+1]
  661. return range_data
  662. def get_correct_product(product,products):
  663. list_data = []
  664. for p in products:
  665. is_sim = is_similar(product,p)
  666. _d = {"product":p,"distance":abs(len(product)-len(p)),"is_sim":is_sim}
  667. list_data.append(_d)
  668. list_data.sort(key=lambda x:x["distance"])
  669. for _d in list_data:
  670. is_sim = _d["is_sim"]
  671. if is_sim:
  672. if len(_d["product"])>len(product) and _d["product"].find(product)>=0:
  673. return product
  674. return _d["product"]
  675. return product
  676. def get_childs_text(childs,_product,products,is_begin=False,is_end=False):
  677. _text = ""
  678. end_next = False
  679. for _child in childs:
  680. child_text = _child.get("text")
  681. if child_text.find(_product)>=0:
  682. if not is_begin:
  683. is_begin = True
  684. if not end_next:
  685. if _child["sentence_title"] is not None and isinstance(_child["title_next"],dict) and _child["title_next"]["sentence_title"] is not None:
  686. end_next = True
  687. end_title = _child["title_next"]
  688. logger.debug("end_title %s "%end_title["text"])
  689. logger.debug("%s-%s-%s"%("get_childs_text",child_text[:10],str(is_begin)))
  690. for p in products:
  691. if child_text.find(p)>=0 and is_similar(_product,p,90):
  692. is_begin = True
  693. if child_text.find(_product)<0 and not is_similar(_product,p,80) and (child_text.find(p)>=0 or _child["has_product"]):
  694. if is_begin:
  695. is_end = True
  696. logger.debug("%s-%s-%s"%("get_childs_text end",child_text[:10],p))
  697. break
  698. if re.search(end_pattern,child_text) is not None:
  699. if is_begin:
  700. is_end = True
  701. logger.debug("%s-%s-%s"%("get_childs_text end",child_text[:10],str(is_end)))
  702. if is_begin and is_end:
  703. break
  704. if is_begin:
  705. _text += _child.get("text")+"\r\n"
  706. childs2 = _child.get("child_title",[])
  707. if len(childs2)>0:
  708. for _child2 in childs2:
  709. child_text,is_begin,is_end = get_childs_text([_child2],_product,products,is_begin)
  710. if is_begin:
  711. _text += child_text
  712. if is_end:
  713. break
  714. if end_next:
  715. is_end = True
  716. # logger.debug("%s-%s-%s"%("get_childs_text1",_text,str(is_begin)))
  717. # logger.debug("%s-%s-%s"%("get_childs_text2",_text,str(is_begin)))
  718. return _text,is_begin,is_end
  719. def extract_parameters_by_tree(_product,products,list_data,_data_i,parent_title,list_result,):
  720. _data = list_data[_data_i]
  721. childs = _data.get("child_title",[])
  722. if len(childs)>0:
  723. child_text,_,_ = get_childs_text([_data],_product,products)
  724. if len(child_text)>0:
  725. logger.info("extract_type by_tree child_text:%s"%child_text)
  726. list_result.append(child_text)
  727. if parent_title is not None:
  728. child_text,_,_ = get_childs_text([parent_title],_product,products)
  729. if len(child_text)>0:
  730. logger.info("extract_type by_tree child_text:%s"%child_text)
  731. list_result.append(child_text)
  732. childs = parent_title.get("child_title",[])
  733. if len(childs)>0:
  734. range_data = get_range_data_by_childs(list_data[_data_i:],childs)
  735. p_text = ""
  736. _find = False
  737. end_id = id(_data["title_next"]) if isinstance(_data["sentence_title"],dict) and _data["title_next"] is not None and _data["title_next"]["sentence_title"] is not None else None
  738. for pdata in range_data:
  739. ptext = pdata["text"]
  740. for p in products:
  741. if ptext.find(_product)<0 and (ptext.find(p)>=0 or pdata["has_product"]):
  742. _find = True
  743. break
  744. if re.search(end_pattern,ptext) is not None:
  745. _find = True
  746. if _find:
  747. break
  748. if id(pdata)==end_id:
  749. break
  750. p_text += ptext+"\r\n"
  751. if len(p_text)>0:
  752. logger.debug("extract_type by parent range_text:%s"%p_text)
  753. list_result.append(p_text)
  754. return True
  755. return False
  756. def get_table_pieces(_text,_product,products,list_result,_find):
  757. _soup = BeautifulSoup(_text,"html5lib")
  758. _table = _soup.find("table")
  759. if _table is not None:
  760. trs = getTrs(_table)
  761. list_trs = []
  762. for tr in trs:
  763. tr_text = tr.get_text()
  764. if tr_text.find(_product)>=0:
  765. _find = True
  766. logger.debug("%s-%s"%("table_html_tr",tr_text))
  767. for p in products:
  768. if _find and p!=_product and tr_text.find(p)>=0:
  769. _find = False
  770. break
  771. if re.search(end_pattern,tr_text) is not None:
  772. _find = False
  773. break
  774. if _find:
  775. list_trs.append(tr)
  776. if len(list_trs)>0:
  777. table_html = "<table>%s</table>"%("\r\n".join([str(a) for a in list_trs]))
  778. logger.debug("extract_type table slices %s"%(table_html))
  779. list_result.append(table_html)
  780. def extract_parameters_by_table(_product,products,_param_pattern,list_data,_data_i,list_result):
  781. _data = list_data[_data_i]
  782. _text = _data["text"]
  783. list_table = _data["list_table"]
  784. parent_title = _data["parent_title"]
  785. if list_table is not None:
  786. _check = True
  787. max_length = max([len(a) for a in list_table])
  788. min_length = min([len(a) for a in list_table])
  789. text_line_first = ",".join(a[0] for a in list_table[0])
  790. if max_length>10:
  791. if min_length<max_length/2:
  792. return
  793. last_data = list_data[_data_i-1]
  794. _flag = False
  795. if last_data["type"]=="sentence" and last_data["text"].find(_product)>=0:
  796. logger.debug("last sentence find product %s-%s"%(_product,last_data["text"]))
  797. _flag = True
  798. # print(text_line_first,"text_line_first",re.search(_param_pattern,text_line_first) is not None and text_line_first.find(_product)>=0)
  799. if re.search(_param_pattern,text_line_first) is not None and text_line_first.find(_product)>=0:
  800. _flag = True
  801. if _flag:
  802. if len(products)==0:
  803. logger.debug("extract_type whole table by param and product %s"%(_text))
  804. list_result.append(_text)
  805. else:
  806. for p in products:
  807. if p!=_product and _text.find(p)>=0:
  808. logger.debug("extract_type add all table failed %s-%s"%(_product,p))
  809. _flag = False
  810. break
  811. if _flag:
  812. logger.debug("extract_type add all table succeed")
  813. get_table_pieces(_text,_product,products,list_result,True)
  814. else:
  815. list_head_index = []
  816. for line in list_table[:2]:
  817. for cell_i in range(len(line)):
  818. cell = line[cell_i]
  819. cell_text = cell[0]
  820. if len(cell_text)<20 and re.search(_param_pattern,cell_text) is not None:
  821. list_head_index.append(cell_i)
  822. list_head_index = list(set(list_head_index))
  823. for line in list_table:
  824. for cell in line:
  825. cell_text = cell[0]
  826. if len(cell_text)>50 and len(re.findall(meter_pattern,cell_text))>5 and cell_text.find(_product)>=0:
  827. _f = True
  828. for cell in line:
  829. if not _f:
  830. break
  831. cell_text = cell[0]
  832. for p in products:
  833. if cell_text.find(p)>=0 and p!=_product:
  834. _f = False
  835. break
  836. if _f:
  837. logger.debug("extract_type param column %s"%(cell_text))
  838. list_result.append(cell_text)
  839. if len(cell_text)<len(_product)*10 and str(cell_text).find(_product)>=0:
  840. for _index in list_head_index:
  841. if _index>=len(line):
  842. continue
  843. _cell = line[_index]
  844. if len(cell[0])>0:
  845. logger.info("%s-%s"%("extract_type add on table text:",_cell[0]))
  846. list_result.append(_cell[0])
  847. if not _flag and (re.search(_param_pattern,_text) is not None or (parent_title is not None and re.search(_param_pattern,parent_title["text"]) is not None)) and _text.find(_product)>=0:
  848. get_table_pieces(_text,_product,products,list_result,False)
  849. def extract_parameters_by_sentence(list_data,_data,_data_i,_product,products,list_result,is_project):
  850. _text = _data["text"]
  851. if _text.find(_product)>=0:
  852. parent_title = _data.get("parent_title")
  853. parent_text = ""
  854. parent_parent_title = None
  855. parent_parent_text = ""
  856. parent_title_index = None
  857. parent_parent_title_index = None
  858. childs = get_childs([_data])
  859. child_find = False
  860. for c in childs:
  861. if re.search(_param_pattern,c["text"]) is not None and len(c["text"])<30:
  862. logger.debug("child text %s"%(c["text"]))
  863. child_find = True
  864. break
  865. extract_text,_,_ = get_childs_text([_data],_product,products)
  866. logger.debug("childs found extract_text %s %s"%(str(child_find),extract_text))
  867. if child_find:
  868. if len(extract_text)>0:
  869. list_result.append(extract_text)
  870. else:
  871. limit_nums = len(_product)*2+5
  872. if len(_product)<=3:
  873. limit_nums += 6
  874. if _text.find("数量")>=0:
  875. limit_nums += 6
  876. if len(_text)<=limit_nums and _data["sentence_title"] is not None:
  877. if re.search(meter_pattern,extract_text) is not None:
  878. list_result.append(extract_text)
  879. elif len(re.findall(meter_pattern,extract_text))>2:
  880. list_result.append(extract_text)
  881. if parent_title is not None:
  882. parent_text = parent_title.get("text","")
  883. parent_parent_title = parent_title.get("parent_title")
  884. parent_title_index = parent_title["title_index"]
  885. if parent_parent_title is not None:
  886. parent_parent_text = parent_parent_title.get("text","")
  887. parent_parent_title_index = parent_parent_title["title_index"]
  888. _suit = False
  889. if re.search(_param_pattern,_text) is not None and len(_text)<50:
  890. _suit = True
  891. if re.search(_param_pattern,parent_text) is not None and len(parent_text)<50:
  892. _suit = True
  893. if re.search(_param_pattern,parent_parent_text) is not None and len(parent_parent_text)<50:
  894. _suit = True
  895. if _suit:
  896. logger.debug("extract_type sentence %s"%("extract_parameters_by_tree"))
  897. if not extract_parameters_by_tree(_product,products,list_data,_data_i,parent_title,list_result):
  898. logger.debug("extract_type sentence %s"%("extract_parameters_by_tree"))
  899. extract_parameters_by_tree(_product,products,list_data,_data_i,parent_parent_title,list_result)
  900. if re.search(_param_pattern,_text) is not None and len(_text)<50:
  901. childs = _data["child_title"]
  902. if len(childs)>0:
  903. extract_text,_,_ = get_childs_text([_data],_product,products)
  904. if len(extract_text)>0:
  905. logger.debug("extract_type param-product %s"%(extract_text))
  906. list_result.append(extract_text)
  907. elif is_project:
  908. extract_text,_,_ = get_childs_text([_data],_product,products,is_begin=True)
  909. if len(extract_text)>0 and re.search(meter_pattern,extract_text) is not None:
  910. logger.debug("extract_type sentence is_project param-product is product %s"%(extract_text))
  911. list_result.append(extract_text)
  912. def getBestProductText(list_result,_product,products):
  913. list_result.sort(key=lambda x:len(re.findall(meter_pattern+"|"+'[::;;]|\d+[%A-Za-z]+',BeautifulSoup(x,"html5lib").get_text())), reverse=True)
  914. logger.debug("+++++++++++++++++++++")
  915. for i in range(len(list_result)):
  916. logger.debug("result%d %s"%(i,list_result[i]))
  917. logger.debug("+++++++++++++++++++++")
  918. for i in range(len(list_result)):
  919. _result = list_result[i]
  920. _check = True
  921. _result_text = BeautifulSoup(_result,"html5lib").get_text()
  922. _search = re.search("项目编号[::]|项目名称[::]|联合体投标|开户银行",_result)
  923. if _search is not None:
  924. logger.debug("result%d error illegal text %s"%(i,str(_search)))
  925. _check = False
  926. if not (len(_result_text)<1000 and _result[:6]!="<table"):
  927. for p in products:
  928. if _result_text.find(p)>0 and not (is_similar(_product,p,80) or p.find(_product)>=0 or _product.find(p)>=0):
  929. logger.debug("result%d error product scoss %s"%(i,p))
  930. _check = False
  931. if len(_result_text)<100:
  932. if re.search(meter_pattern,_result_text) is None:
  933. logger.debug("result%d error text min count"%(i))
  934. _check = False
  935. if len(_result_text)>5000:
  936. if len(_result_text)>10000:
  937. logger.debug("result%d error text max count"%(i))
  938. _check = False
  939. elif len(re.findall(meter_pattern,_result_text))<10:
  940. logger.debug("result%d error text max count less meter"%(i))
  941. _check = False
  942. list_find = list(set(re.findall(meter_pattern,_result_text)))
  943. not_list_find = list(set(re.findall(not_meter_pattern,_result_text)))
  944. _count = len(list_find)-len(not_list_find)
  945. has_num = False
  946. for _find in list_find:
  947. if re.search('[0-9a-zA-Z]',_find) is not None:
  948. has_num = True
  949. break
  950. if not(_count>=2 and has_num or _count>=5):
  951. logger.debug("result%d error match not enough"%(i))
  952. _check = False
  953. if _check:
  954. return _result
  955. def format_text(_result):
  956. list_result = re.split("\r|\n",_result)
  957. _result = ""
  958. for _r in list_result:
  959. if len(_r)>0:
  960. _result+="%s\n"%(_r)
  961. _result = '<div style="white-space:pre">%s</div>'%(_result)
  962. return _result
  963. def extract_product_parameters(list_data,_product):
  964. list_result = []
  965. _product = standard_product(_product.strip())
  966. products = extract_products(list_data,_product)
  967. _product = get_correct_product(_product,products)
  968. logger.debug("all products %s-%s"%(_product,str(products)))
  969. is_project = False
  970. if re.search("项目名称|采购项目",_product) is not None:
  971. is_project = True
  972. if len(products)==1 and is_similar(products[0],_product,90):
  973. is_project = True
  974. _find_count = 0
  975. for _data_i in range(len(list_data)):
  976. _data = list_data[_data_i]
  977. _type = _data["type"]
  978. _text = _data["text"]
  979. if _type=="sentence":
  980. if _text.find(_product)>=0:
  981. _find_count += 1
  982. if re.search("项目名称|采购项目",_text) is not None and re.search("等",_text) is not None:
  983. is_project = True
  984. extract_parameters_by_sentence(list_data,_data,_data_i,_product,products,list_result,is_project)
  985. elif _type=="table":
  986. if _text.find(_product)>=0:
  987. _find_count += 1
  988. extract_parameters_by_table(_product,products,_param_pattern,list_data,_data_i,list_result)
  989. _text = getBestProductText(list_result,_product,products)
  990. return _text,_find_count
  991. if __name__ == '__main__':
  992. filepath = "download/4597dcc128bfabc7584d10590ae50656.html"
  993. _product = "彩色多普勒超声诊断仪"
  994. _html = open(filepath, "r", encoding="utf8").read()
  995. pd = ParseDocument(_html,False)
  996. pd.fix_tree(_product)
  997. list_data = pd.tree
  998. pd.print_tree(list_data)
  999. _text,_count = extract_product_parameters(list_data,_product)
  1000. logger.info("find count:%d"%(_count))
  1001. logger.info("extract_parameter_text::%s"%(_text))