outline_extractor.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. """
  4. @author: bidikeji
  5. @time: 2024/7/19 10:05
  6. """
  7. import re
  8. from BiddingKG.dl.interface.htmlparser import ParseDocument,get_childs
  9. class Sentence2():
  10. def __init__(self,text,sentence_index,wordOffset_begin,wordOffset_end):
  11. self.name = 'sentence2'
  12. self.text = text
  13. self.sentence_index = sentence_index
  14. self.wordOffset_begin = wordOffset_begin
  15. self.wordOffset_end = wordOffset_end
  16. def get_text(self):
  17. return self.text
  18. def extract_sentence_list(sentence_list):
  19. new_sentence2_list = []
  20. new_sentence2_list_attach = []
  21. for sentence in sentence_list:
  22. sentence_index = sentence.sentence_index
  23. sentence_text = sentence.sentence_text
  24. begin_index = 0
  25. end_index = 0
  26. for it in re.finditer('([^一二三四五六七八九十,。][一二三四五六七八九十]{1,3}|[^\d\.、,。a-zA-Z]\d{1,2}(\.\d{1,2}){,2})、', sentence_text): # 例:289699210 1、招标内容:滑触线及配件2、招标品牌:3、参标供应商经营形式要求:厂家4、参标供应商资质要求:5、
  27. temp = it.group(0)
  28. sentence_text = sentence_text.replace(temp, temp[0] + ',' + temp[1:])
  29. for item in re.finditer('[,。;;!!?]+', sentence_text): # 20240725去掉英文问号,避免网址被分隔
  30. end_index = item.end()
  31. # if end_index!=len(sentence_text):
  32. # # if end_index-begin_index<6 and item.group(0) in [',', ';', ';'] and re.match('[一二三四五六七八九十\d.]+、', sentence_text[begin_index:end_index])==None: # 20240725 注销,避免标题提取错误
  33. # # continue
  34. if end_index != len(sentence_text) and re.match('[一二三四五六七八九十\d.]{1,2}[、,.]+$', sentence_text[begin_index:end_index]): # 避免表格序号和内容在不同表格情况 例:293178161
  35. continue
  36. new_sentence_text = sentence_text[begin_index:end_index]
  37. sentence2 = Sentence2(new_sentence_text,sentence_index,begin_index,end_index)
  38. if sentence.in_attachment:
  39. new_sentence2_list_attach.append(sentence2)
  40. else:
  41. new_sentence2_list.append(sentence2)
  42. begin_index = end_index
  43. if end_index!=len(sentence_text):
  44. end_index = len(sentence_text)
  45. new_sentence_text = sentence_text[begin_index:end_index]
  46. sentence2 = Sentence2(new_sentence_text, sentence_index, begin_index, end_index)
  47. if sentence.in_attachment:
  48. new_sentence2_list_attach.append(sentence2)
  49. else:
  50. new_sentence2_list.append(sentence2)
  51. return new_sentence2_list, new_sentence2_list_attach
  52. requirement_pattern = "(采购需求|需求分析|项目说明|(采购|合同|招标|询比?价|项目|服务|工程|标的|需求|建设)(的?(主要|简要|基本|具体|名称及))?" \
  53. "(内容|概况|概述|范围|信息|规模|简介|介绍|说明|摘要|情况)([及与和]((其它|\w{,2})[要需]求|发包范围|数量))?" \
  54. "|招标项目技术要求|服务要求|服务需求|项目目标|需求内容如下|建设规模)为?([::,]|$)"
  55. aptitude_pattern = "(资格要求|资质要求)([::,]|$)"
  56. addr_bidopen_pattern = "([开评]标|开启|评选|比选|磋商|遴选|寻源|采购|招标|竞价|议价|委托|询比?价|比价|谈判|邀标|邀请|洽谈|约谈|选取|抽取|抽选|递交\w{,4}文件)[))]?(时间[与及和、])?(地址|地点)([与及和、]时间)?([::,]|$)|开启([::,]|$)"
  57. addr_bidsend_pattern = "((\w{,4}文件)?(提交|递交)(\w{,4}文件)?|投标)(截止时间[与及和、])?地[点址]([与及和、]截止时间)?([::,]|$)"
  58. out_lines = []
  59. def extract_parameters(parse_document, content):
  60. '''
  61. 通过大纲、预处理后文本正则获取需要字段
  62. :param parse_document: ParseDocument() 方法返回结果
  63. :param content: 公告预处理后文本
  64. :return:
  65. '''
  66. list_data = parse_document.tree
  67. requirement_text = ''
  68. aptitude_text = ''
  69. addr_bidopen_text = ''
  70. addr_bidsend_text = ''
  71. _find_count = 0
  72. _data_i = -1
  73. while _data_i<len(list_data)-1:
  74. _data_i += 1
  75. _data = list_data[_data_i]
  76. _type = _data["type"]
  77. _text = _data["text"].strip()
  78. # print(_data.keys())
  79. if _type=="sentence":
  80. if _data["sentence_title"] is not None:
  81. if re.search('[((][一二三四五六七八九十]+[))]|[一二三四五六七八九十]+\s*、', _text[:10]):
  82. out_lines.append((_text, _data['sentence_index'], _data['wordOffset_begin']))
  83. if re.search(requirement_pattern,_text[:30]) is not None and re.search('符合采购需求,', _text[:30])==None:
  84. childs = get_childs([_data])
  85. for c in childs:
  86. # requirement_text += c["text"]+"\n"
  87. requirement_text += c["text"]
  88. _data_i += len(childs)
  89. _data_i -= 1
  90. _data_i = -1
  91. while _data_i<len(list_data)-1:
  92. _data_i += 1
  93. _data = list_data[_data_i]
  94. _type = _data["type"]
  95. _text = _data["text"].strip()
  96. # print(_data.keys())
  97. if _type=="sentence":
  98. # print("aptitude_pattern", _text)
  99. if _data["sentence_title"] is not None:
  100. # print("aptitude_pattern",_text)
  101. # outline = re.sub('(?[一二三四五六七八九十\d.]+)?\s*、?', '',
  102. # re.split('[::,]', _text)[0].replace('(', '(').replace(')', ')'))
  103. if re.search(aptitude_pattern,_text[:30]) is not None:
  104. childs = get_childs([_data])
  105. for c in childs:
  106. aptitude_text += c["text"]
  107. # if c["sentence_title"]:
  108. # aptitude_text += c["text"]+"\n"
  109. # else:
  110. # aptitude_text += c["text"]
  111. _data_i += len(childs)
  112. _data_i -= 1
  113. # elif re.match('[((\s★▲\*]?[一二三四五六七八九十\dⅠⅡⅢⅣⅤⅥⅦⅧⅨⅩⅪⅫ]+', _text) and len(_text)<30 and re.search('资质|资格', _text):
  114. # out_lines.append(outline)
  115. if _type=="table":
  116. list_table = _data["list_table"]
  117. parent_title = _data["parent_title"]
  118. if list_table is not None:
  119. for line in list_table[:2]:
  120. for cell_i in range(len(line)):
  121. cell = line[cell_i]
  122. cell_text = cell[0]
  123. if len(cell_text)>120 and re.search(aptitude_pattern,cell_text) is not None:
  124. aptitude_text += cell_text+"\n"
  125. _data_i = -1
  126. while _data_i < len(list_data) - 1:
  127. _data_i += 1
  128. _data = list_data[_data_i]
  129. _type = _data["type"]
  130. _text = _data["text"].strip()
  131. # print(_data.keys())
  132. if _type == "sentence":
  133. if _data["sentence_title"] is not None:
  134. if re.search(addr_bidopen_pattern, _text[:20]) is not None:
  135. childs = get_childs([_data], max_depth=1)
  136. for c in childs:
  137. addr_bidopen_text += c["text"]
  138. _data_i += len(childs)
  139. _data_i -= 1
  140. elif re.search(addr_bidsend_pattern, _text[:20]):
  141. childs = get_childs([_data], max_depth=1)
  142. for c in childs:
  143. addr_bidsend_text += c["text"]
  144. _data_i += len(childs)
  145. _data_i -= 1
  146. if re.search('时间:', addr_bidopen_text) and re.search('([开评]标|开启|评选|比选|递交\w{,4}文件)?地[点址]([((]网址[))])?:[^,;。]{2,100}[,;。]', addr_bidopen_text):
  147. for ser in re.finditer('([开评]标|开启|评选|比选|递交\w{,4}文件)?地[点址]([((]网址[))])?:[^,;。]{2,100}[,;。]', addr_bidopen_text):
  148. b, e = ser.span()
  149. addr_bidopen_text = addr_bidopen_text[b:e]
  150. elif re.search('开启', addr_bidopen_text) and re.search('时间:\d{2,4}年\d{1,2}月\d{1,2}日', addr_bidopen_text) and len(addr_bidopen_text)<40: # 优化类似 364991684只有时间没地址情况
  151. addr_bidopen_text = ""
  152. if addr_bidopen_text == "":
  153. ser = re.search('([开评]标|开启|评选|比选|磋商|遴选|寻源|采购|招标|竞价|议价|委托|询比?价|比价|谈判|邀标|邀请|洽谈|约谈|选取|抽取|抽选|递交\w{,4}文件))?(会议)?地[点址]([((]网址[))])?[:为][^,;。]{2,100}[,;。]', content)
  154. if ser:
  155. addr_bidopen_text = ser.group(0)
  156. if re.search('时间:', addr_bidsend_text) and re.search('((\w{,4}文件)?(提交|递交)(\w{,4}文件)?|投标)?地[点址]([((]网址[))])?:[^,;。]{2,100}[,;。]', addr_bidsend_text):
  157. for ser in re.finditer('((\w{,4}文件)?(提交|递交)(\w{,4}文件)?|投标)?地[点址]([((]网址[))])?:[^,;。]{2,100}[,;。]', addr_bidsend_text):
  158. b, e = ser.span()
  159. addr_bidsend_text = addr_bidsend_text[b:e]
  160. return requirement_text, aptitude_text, addr_bidopen_text, addr_bidsend_text, out_lines
  161. if __name__ == "__main__":
  162. # with open('D:\html/2.html', 'r', encoding='UTF-8') as f:
  163. # html = f.read()
  164. #
  165. l = []
  166. import pandas as pd
  167. from collections import Counter
  168. from BiddingKG.dl.interface import Preprocessing
  169. from BiddingKG.dl.interface.get_label_dic import get_all_label
  170. from bs4 import BeautifulSoup
  171. import json
  172. df = pd.read_excel('E:/公告招标内容提取结果2.xlsx')
  173. df['len']= df['招标内容'].apply(lambda x: len(x))
  174. print(len(df), sum(df['len']),sum(df['len'])/len(df), max(df['len']), min(df['len']))
  175. print(len([it for it in df['len'] if it>1500]))
  176. # df = pd.read_csv(r'E:\channel分类数据\2022年每月两天数据/指定日期_html2022-12-10.csv')
  177. # df1 = pd.read_excel('E:/公告招标内容提取结果.xlsx')
  178. # df = df[df['docid'].isin(df1['docid'])]
  179. #
  180. # df.drop_duplicates(subset=['docchannel', 'web_source_name', 'exist_table'], inplace=True)
  181. # print(df.columns, len(df))
  182. #
  183. #
  184. # # def get_text(html):
  185. # # soup = BeautifulSoup(html, 'lxml')
  186. # # text = soup.get_text()
  187. # # return text
  188. # # df['content'] = df['dochtmlcon'].apply(lambda x: get_text(x))
  189. # # df['标签'] = df.apply(lambda x: get_all_label(x['doctitle'], x['content']), axis=1)
  190. # # df['标签'] = df['标签'].apply(lambda x: json.dumps(x, ensure_ascii=False, indent=2))
  191. # # df1 = df[['docid', '标签']]
  192. #
  193. # n = 0
  194. # datas = []
  195. # for id,title, html in zip(df['docid'],df['doctitle'], df['dochtmlcon']):
  196. # # if id not in [289647738, 289647739]:
  197. # # continue
  198. # # print(id, type(id))
  199. # # parse_document = ParseDocument(html, True)
  200. # # requirement_text, aptitude_text = extract_parameters(parse_document)
  201. # # if re.search('资\s*[格质]', html)==None:
  202. # # continue
  203. #
  204. # list_articles, list_sentences, list_entitys, list_outlines, _cost_time = Preprocessing.get_preprocessed([[id,html,"","",title,'', '']],useselffool=True)
  205. # sentence2_list, sentence2_list_attach = extract_sentence_list(list_sentences[0])
  206. #
  207. # # sentence2_list = []
  208. #
  209. # parse_document = ParseDocument(html, True, list_obj=sentence2_list)
  210. # requirement_text, aptitude_text = extract_parameters(parse_document)
  211. # # if len(aptitude_text)>0:
  212. # # datas.append((id, aptitude_text[:1500]))
  213. # # print(id, aptitude_text[:10], aptitude_text[-20:])
  214. # # else:
  215. # # parse_document = ParseDocument(html, True, list_obj=sentence2_list_attach)
  216. # # requirement_text, aptitude_text = extract_parameters(parse_document)
  217. #
  218. # # if 0<len(aptitude_text)<20:
  219. # # l.append(len(aptitude_text))
  220. # # n += 1
  221. # # print(id, aptitude_text)
  222. # # if n > 5:
  223. # # break
  224. #
  225. # if len(requirement_text)>0:
  226. # label_dic = get_all_label(title, list_articles[0].content)
  227. # # datas.append((id, requirement_text))
  228. # datas.append((id, requirement_text, label_dic))
  229. #
  230. # c = Counter(out_lines)
  231. # print(c.most_common(1000))
  232. # #
  233. # # df = pd.DataFrame(datas, columns=['docid', '资质要求'])
  234. # # df.to_excel('E:/公告资质要求提取结果.xlsx')
  235. #
  236. # df = pd.DataFrame(datas, columns=['docid', '招标内容', '标签'])
  237. # df['标签'] = df['标签'].apply(lambda x: json.dumps(x, ensure_ascii=False, indent=2))
  238. # df.to_excel('E:/公告招标内容提取结果2.xlsx')
  239. # if len(aptitude_text)> 1000:
  240. # print(id, aptitude_text[:10], aptitude_text[-20:])
  241. # print(Counter(l).most_common(50))
  242. # print(len(df), len(l), min(l), max(l), sum(l)/len(l))
  243. # n1 = len([it for it in l if it < 500])
  244. # n2 = len([it for it in l if it < 1000])
  245. # n3 = len([it for it in l if it < 1500])
  246. # n4 = len([it for it in l if it < 2000])
  247. # print(n1, n2, n3, n4, n1/len(l), n2/len(l), n3/len(l), n4/len(l))
  248. # parse_document = ParseDocument(html,True)
  249. # requirement_text, new_list_policy, aptitude_text = extract_parameters(parse_document)
  250. # print(aptitude_text)
  251. # sentence_text = '5、要求:3.1投标其他条件:1、中国宝武集团项目未列入禁入名单的投标人。2、具有有效的营业执照;'
  252. # begin_index = 0
  253. # for item in re.finditer('[,。;;!!??]+', sentence_text):
  254. # end_index = item.end()
  255. # if end_index != len(sentence_text):
  256. # if end_index - begin_index < 6:
  257. # continue
  258. # new_sentence_text = sentence_text[begin_index:end_index]
  259. # print(new_sentence_text)
  260. # df = pd.read_excel('E:/公告资质要求提取结果.xlsx')
  261. # docids = []
  262. # pos = neg = 0
  263. # for docid, text in zip(df['docid'], df['资质要求']):
  264. # if re.match('[((\s★▲\*]?[一二三四五六七八九十\dⅠⅡⅢⅣⅤⅥⅦⅧⅨⅩⅪⅫ]+', text) and re.search(aptitude_pattern, text[:15]):
  265. # pos += 1
  266. # pass
  267. # else:
  268. # neg += 1
  269. # print(docid, text[:50])
  270. # docids.append(docid)
  271. # print('异常:%d, 正常:%d'%(neg, pos))
  272. # print(docids)