htmlparser.py 60 KB

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