htmlparser.py 59 KB

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