Preprocessing.py 109 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252
  1. # -*- coding: utf-8 -*-
  2. from bs4 import BeautifulSoup, Comment
  3. import copy
  4. import sys
  5. import os
  6. import time
  7. import codecs
  8. sys.setrecursionlimit(1000000)
  9. sys.path.append(os.path.abspath("../.."))
  10. sys.path.append(os.path.abspath(".."))
  11. from BiddingKG.dl.common.Utils import *
  12. from BiddingKG.dl.interface.Entitys import *
  13. from BiddingKG.dl.interface.predictor import getPredictor
  14. from BiddingKG.dl.common.nerUtils import *
  15. from BiddingKG.dl.money.moneySource.ruleExtra import extract_moneySource
  16. from BiddingKG.dl.time.re_servicetime import extract_servicetime
  17. from BiddingKG.dl.relation_extraction.re_email import extract_email
  18. from BiddingKG.dl.bidway.re_bidway import extract_bidway,bidway_integrate
  19. from BiddingKG.dl.fingerprint.documentFingerprint import getFingerprint
  20. from BiddingKG.dl.entityLink.entityLink import *
  21. #
  22. def tableToText(soup):
  23. '''
  24. @param:
  25. soup:网页html的soup
  26. @return:处理完表格信息的网页text
  27. '''
  28. def getTrs(tbody):
  29. #获取所有的tr
  30. trs = []
  31. objs = tbody.find_all(recursive=False)
  32. for obj in objs:
  33. if obj.name=="tr":
  34. trs.append(obj)
  35. if obj.name=="tbody":
  36. for tr in obj.find_all("tr",recursive=False):
  37. trs.append(tr)
  38. return trs
  39. def fixSpan(tbody):
  40. # 处理colspan, rowspan信息补全问题
  41. #trs = tbody.findChildren('tr', recursive=False)
  42. trs = getTrs(tbody)
  43. ths_len = 0
  44. ths = list()
  45. trs_set = set()
  46. #修改为先进行列补全再进行行补全,否则可能会出现表格解析混乱
  47. # 遍历每一个tr
  48. for indtr, tr in enumerate(trs):
  49. ths_tmp = tr.findChildren('th', recursive=False)
  50. #不补全含有表格的tr
  51. if len(tr.findChildren('table'))>0:
  52. continue
  53. if len(ths_tmp) > 0:
  54. ths_len = ths_len + len(ths_tmp)
  55. for th in ths_tmp:
  56. ths.append(th)
  57. trs_set.add(tr)
  58. # 遍历每行中的element
  59. tds = tr.findChildren(recursive=False)
  60. for indtd, td in enumerate(tds):
  61. # 若有colspan 则补全同一行下一个位置
  62. if 'colspan' in td.attrs:
  63. if str(re.sub("[^0-9]","",str(td['colspan'])))!="":
  64. col = int(re.sub("[^0-9]","",str(td['colspan'])))
  65. if col<100 and len(td.get_text())<1000:
  66. td['colspan'] = 1
  67. for i in range(1, col, 1):
  68. td.insert_after(copy.copy(td))
  69. for indtr, tr in enumerate(trs):
  70. ths_tmp = tr.findChildren('th', recursive=False)
  71. #不补全含有表格的tr
  72. if len(tr.findChildren('table'))>0:
  73. continue
  74. if len(ths_tmp) > 0:
  75. ths_len = ths_len + len(ths_tmp)
  76. for th in ths_tmp:
  77. ths.append(th)
  78. trs_set.add(tr)
  79. # 遍历每行中的element
  80. tds = tr.findChildren(recursive=False)
  81. for indtd, td in enumerate(tds):
  82. # 若有rowspan 则补全下一行同样位置
  83. if 'rowspan' in td.attrs:
  84. if str(re.sub("[^0-9]","",str(td['rowspan'])))!="":
  85. row = int(re.sub("[^0-9]","",str(td['rowspan'])))
  86. td['rowspan'] = 1
  87. for i in range(1, row, 1):
  88. # 获取下一行的所有td, 在对应的位置插入
  89. if indtr+i<len(trs):
  90. tds1 = trs[indtr + i].findChildren(['td','th'], recursive=False)
  91. if len(tds1) >= (indtd) and len(tds1)>0:
  92. if indtd > 0:
  93. tds1[indtd - 1].insert_after(copy.copy(td))
  94. else:
  95. tds1[0].insert_before(copy.copy(td))
  96. elif indtd-2>0 and len(tds1) > 0 and len(tds1) == indtd - 1: # 修正某些表格最后一列没补全
  97. tds1[indtd-2].insert_after(copy.copy(td))
  98. def getTable(tbody):
  99. #trs = tbody.findChildren('tr', recursive=False)
  100. trs = getTrs(tbody)
  101. inner_table = []
  102. for tr in trs:
  103. tr_line = []
  104. tds = tr.findChildren(['td','th'], recursive=False)
  105. if len(tds)==0:
  106. tr_line.append([re.sub('\xa0','',segment(tr,final=False)),0]) # 2021/12/21 修复部分表格没有td 造成数据丢失
  107. for td in tds:
  108. tr_line.append([re.sub('\xa0','',segment(td,final=False)),0])
  109. #tr_line.append([td.get_text(),0])
  110. inner_table.append(tr_line)
  111. return inner_table
  112. #处理表格不对齐的问题
  113. def fixTable(inner_table,fix_value="~~"):
  114. maxWidth = 0
  115. for item in inner_table:
  116. if len(item)>maxWidth:
  117. maxWidth = len(item)
  118. for i in range(len(inner_table)):
  119. if len(inner_table[i])<maxWidth:
  120. for j in range(maxWidth-len(inner_table[i])):
  121. inner_table[i].append([fix_value,0])
  122. return inner_table
  123. def removePadding(inner_table,pad_row = "@@",pad_col = "##"):
  124. height = len(inner_table)
  125. width = len(inner_table[0])
  126. for i in range(height):
  127. point = ""
  128. for j in range(width):
  129. if inner_table[i][j][0]==point and point!="":
  130. inner_table[i][j][0] = pad_row
  131. else:
  132. if inner_table[i][j][0] not in [pad_row,pad_col]:
  133. point = inner_table[i][j][0]
  134. for j in range(width):
  135. point = ""
  136. for i in range(height):
  137. if inner_table[i][j][0]==point and point!="":
  138. inner_table[i][j][0] = pad_col
  139. else:
  140. if inner_table[i][j][0] not in [pad_row,pad_col]:
  141. point = inner_table[i][j][0]
  142. def addPadding(inner_table,pad_row = "@@",pad_col = "##"):
  143. height = len(inner_table)
  144. width = len(inner_table[0])
  145. for i in range(height):
  146. for j in range(width):
  147. if inner_table[i][j][0]==pad_row:
  148. inner_table[i][j][0] = inner_table[i][j-1][0]
  149. inner_table[i][j][1] = inner_table[i][j-1][1]
  150. if inner_table[i][j][0]==pad_col:
  151. inner_table[i][j][0] = inner_table[i-1][j][0]
  152. inner_table[i][j][1] = inner_table[i-1][j][1]
  153. def repairTable(inner_table,dye_set = set(),key_set = set(),fix_value="~~"):
  154. '''
  155. @summary: 修复表头识别,将明显错误的进行修正
  156. '''
  157. def repairNeeded(line):
  158. first_1 = -1
  159. last_1 = -1
  160. first_0 = -1
  161. last_0 = -1
  162. count_1 = 0
  163. count_0 = 0
  164. for i in range(len(line)):
  165. if line[i][0]==fix_value:
  166. continue
  167. if line[i][1]==1:
  168. if first_1==-1:
  169. first_1 = i
  170. last_1 = i
  171. count_1 += 1
  172. if line[i][1]==0:
  173. if first_0 == -1:
  174. first_0 = i
  175. last_0 = i
  176. count_0 += 1
  177. if first_1 ==-1 or last_0 == -1:
  178. return False
  179. #异常情况:第一个不是表头;最后一个是表头;表头个数远大于属性值个数
  180. if first_1-0>0 or last_0-len(line)+1<0 or last_1==len(line)-1 or count_1-count_0>=3:
  181. return True
  182. return False
  183. def getsimilarity(line,line1):
  184. same_count = 0
  185. for item,item1 in zip(line,line1):
  186. if item[1]==item1[1]:
  187. same_count += 1
  188. return same_count/len(line)
  189. def selfrepair(inner_table,index,dye_set,key_set):
  190. '''
  191. @summary: 计算每个节点受到的挤压度来判断是否需要染色
  192. '''
  193. #print("B",inner_table[index])
  194. min_presure = 3
  195. list_dye = []
  196. first = None
  197. count = 0
  198. temp_set = set()
  199. _index = 0
  200. for item in inner_table[index]:
  201. if first is None:
  202. first = item[1]
  203. if item[0] not in temp_set:
  204. count += 1
  205. temp_set.add(item[0])
  206. else:
  207. if first == item[1]:
  208. if item[0] not in temp_set:
  209. temp_set.add(item[0])
  210. count += 1
  211. else:
  212. list_dye.append([first,count,_index])
  213. first = item[1]
  214. temp_set.add(item[0])
  215. count = 1
  216. _index += 1
  217. list_dye.append([first,count,_index])
  218. if len(list_dye)>1:
  219. begin = 0
  220. end = 0
  221. for i in range(len(list_dye)):
  222. end = list_dye[i][2]
  223. dye_flag = False
  224. #首尾要求压力减一
  225. if i==0:
  226. if list_dye[i+1][1]-list_dye[i][1]+1>=min_presure-1:
  227. dye_flag = True
  228. dye_type = list_dye[i+1][0]
  229. elif i==len(list_dye)-1:
  230. if list_dye[i-1][1]-list_dye[i][1]+1>=min_presure-1:
  231. dye_flag = True
  232. dye_type = list_dye[i-1][0]
  233. else:
  234. if list_dye[i][1]>1:
  235. if list_dye[i+1][1]-list_dye[i][1]+1>=min_presure:
  236. dye_flag = True
  237. dye_type = list_dye[i+1][0]
  238. if list_dye[i-1][1]-list_dye[i][1]+1>=min_presure:
  239. dye_flag = True
  240. dye_type = list_dye[i-1][0]
  241. else:
  242. if list_dye[i+1][1]+list_dye[i-1][1]-list_dye[i][1]+1>=min_presure:
  243. dye_flag = True
  244. dye_type = list_dye[i+1][0]
  245. if list_dye[i+1][1]+list_dye[i-1][1]-list_dye[i][1]+1>=min_presure:
  246. dye_flag = True
  247. dye_type = list_dye[i-1][0]
  248. if dye_flag:
  249. for h in range(begin,end):
  250. inner_table[index][h][1] = dye_type
  251. dye_set.add((inner_table[index][h][0],dye_type))
  252. key_set.add(inner_table[index][h][0])
  253. begin = end
  254. #print("E",inner_table[index])
  255. def otherrepair(inner_table,index,dye_set,key_set):
  256. list_provide_repair = []
  257. if index==0 and len(inner_table)>1:
  258. list_provide_repair.append(index+1)
  259. elif index==len(inner_table)-1:
  260. list_provide_repair.append(index-1)
  261. else:
  262. list_provide_repair.append(index+1)
  263. list_provide_repair.append(index-1)
  264. for provide_index in list_provide_repair:
  265. if not repairNeeded(inner_table[provide_index]):
  266. same_prob = getsimilarity(inner_table[index], inner_table[provide_index])
  267. if same_prob>=0.8:
  268. for i in range(len(inner_table[provide_index])):
  269. if inner_table[index][i][1]!=inner_table[provide_index][i][1]:
  270. dye_set.add((inner_table[index][i][0],inner_table[provide_index][i][1]))
  271. key_set.add(inner_table[index][i][0])
  272. inner_table[index][i][1] = inner_table[provide_index][i][1]
  273. elif same_prob<=0.2:
  274. for i in range(len(inner_table[provide_index])):
  275. if inner_table[index][i][1]==inner_table[provide_index][i][1]:
  276. dye_set.add((inner_table[index][i][0],inner_table[provide_index][i][1]))
  277. key_set.add(inner_table[index][i][0])
  278. inner_table[index][i][1] = 0 if inner_table[provide_index][i][1] ==1 else 1
  279. len_dye_set = len(dye_set)
  280. height = len(inner_table)
  281. for i in range(height):
  282. if repairNeeded(inner_table[i]):
  283. selfrepair(inner_table,i,dye_set,key_set)
  284. #otherrepair(inner_table,i,dye_set,key_set)
  285. for h in range(len(inner_table)):
  286. for w in range(len(inner_table[0])):
  287. if inner_table[h][w][0] in key_set:
  288. for item in dye_set:
  289. if inner_table[h][w][0]==item[0]:
  290. inner_table[h][w][1] = item[1]
  291. #如果两个set长度不相同,则有同一个key被反复染色,将导致无限迭代
  292. if len(dye_set)!=len(key_set):
  293. for i in range(height):
  294. if repairNeeded(inner_table[i]):
  295. selfrepair(inner_table,i,dye_set,key_set)
  296. #otherrepair(inner_table,i,dye_set,key_set)
  297. return
  298. if len(dye_set)==len_dye_set:
  299. '''
  300. for i in range(height):
  301. if repairNeeded(inner_table[i]):
  302. otherrepair(inner_table,i,dye_set,key_set)
  303. '''
  304. return
  305. repairTable(inner_table, dye_set, key_set)
  306. def sliceTable(inner_table,fix_value="~~"):
  307. #进行分块
  308. height = len(inner_table)
  309. width = len(inner_table[0])
  310. head_list = []
  311. head_list.append(0)
  312. last_head = None
  313. last_is_same_value = False
  314. for h in range(height):
  315. is_all_key = True#是否是全表头行
  316. is_all_value = True#是否是全属性值
  317. is_same_with_lastHead = True#和上一行的结构是否相同
  318. is_same_value=True#一行的item都一样
  319. #is_same_first_item = True#与上一行的第一项是否相同
  320. same_value = inner_table[h][0][0]
  321. for w in range(width):
  322. if last_head is not None:
  323. if inner_table[h-1][w][0]!=fix_value and inner_table[h-1][w][1] == 0:
  324. is_all_key = False
  325. if inner_table[h][w][0]==1:
  326. is_all_value = False
  327. if inner_table[h][w][1]!= inner_table[h-1][w][1]:
  328. is_same_with_lastHead = False
  329. if inner_table[h][w][0]!=fix_value and inner_table[h][w][0]!=same_value:
  330. is_same_value = False
  331. else:
  332. if re.search("\d+",same_value) is not None:
  333. is_same_value = False
  334. if h>0 and inner_table[h][0][0]!=inner_table[h-1][0][0]:
  335. is_same_first_item = False
  336. last_head = h
  337. if last_is_same_value:
  338. last_is_same_value = is_same_value
  339. continue
  340. if is_same_value:
  341. head_list.append(h)
  342. last_is_same_value = is_same_value
  343. continue
  344. if not is_all_key:
  345. if not is_same_with_lastHead:
  346. head_list.append(h)
  347. head_list.append(height)
  348. return head_list
  349. def setHead_initem(inner_table,pat_head,fix_value="~~",prob_min=0.5):
  350. set_item = set()
  351. height = len(inner_table)
  352. width = len(inner_table[0])
  353. for i in range(height):
  354. for j in range(width):
  355. item = inner_table[i][j][0]
  356. set_item.add(item)
  357. list_item = list(set_item)
  358. x = []
  359. for item in list_item:
  360. x.append(getPredictor("form").encode(item))
  361. predict_y = getPredictor("form").predict(np.array(x),type="item")
  362. _dict = dict()
  363. for item,values in zip(list_item,list(predict_y)):
  364. _dict[item] = values[1]
  365. # print("##",item,values)
  366. #print(_dict)
  367. for i in range(height):
  368. for j in range(width):
  369. item = inner_table[i][j][0]
  370. inner_table[i][j][1] = 1 if _dict[item]>prob_min else (1 if re.search(pat_head,item) is not None and len(item)<8 else 0)
  371. # print("=====")
  372. # for item in inner_table:
  373. # print(item)
  374. # print("======")
  375. repairTable(inner_table)
  376. head_list = sliceTable(inner_table)
  377. return inner_table,head_list
  378. def setHead_incontext(inner_table,pat_head,fix_value="~~",prob_min=0.5):
  379. data_x,data_position = getPredictor("form").getModel("context").encode(inner_table)
  380. predict_y = getPredictor("form").getModel("context").predict(data_x)
  381. for _position,_y in zip(data_position,predict_y):
  382. _w = _position[0]
  383. _h = _position[1]
  384. if _y[1]>prob_min:
  385. inner_table[_h][_w][1] = 1
  386. else:
  387. inner_table[_h][_w][1] = 0
  388. _item = inner_table[_h][_w][0]
  389. if re.search(pat_head,_item) is not None and len(_item)<8:
  390. inner_table[_h][_w][1] = 1
  391. # print("=====")
  392. # for item in inner_table:
  393. # print(item)
  394. # print("======")
  395. height = len(inner_table)
  396. width = len(inner_table[0])
  397. for i in range(height):
  398. for j in range(width):
  399. if re.search("[::]$", inner_table[i][j][0]) and len(inner_table[i][j][0])<8:
  400. inner_table[i][j][1] = 1
  401. repairTable(inner_table)
  402. head_list = sliceTable(inner_table)
  403. # print("inner_table:",inner_table)
  404. return inner_table,head_list
  405. #设置表头
  406. def setHead_inline(inner_table,prob_min=0.64):
  407. pad_row = "@@"
  408. pad_col = "##"
  409. removePadding(inner_table, pad_row, pad_col)
  410. pad_pattern = re.compile(pad_row+"|"+pad_col)
  411. height = len(inner_table)
  412. width = len(inner_table[0])
  413. head_list = []
  414. head_list.append(0)
  415. #行表头
  416. is_head_last = False
  417. for i in range(height):
  418. is_head = False
  419. is_long_value = False
  420. #判断是否是全padding值
  421. is_same_value = True
  422. same_value = inner_table[i][0][0]
  423. for j in range(width):
  424. if inner_table[i][j][0]!=same_value and inner_table[i][j][0]!=pad_row:
  425. is_same_value = False
  426. break
  427. #predict is head or not with model
  428. temp_item = ""
  429. for j in range(width):
  430. temp_item += inner_table[i][j][0]+"|"
  431. temp_item = re.sub(pad_pattern,"",temp_item)
  432. form_prob = getPredictor("form").predict(formEncoding(temp_item,expand=True),type="line")
  433. if form_prob is not None:
  434. if form_prob[0][1]>prob_min:
  435. is_head = True
  436. else:
  437. is_head = False
  438. #print(temp_item,form_prob)
  439. if len(inner_table[i][0][0])>40:
  440. is_long_value = True
  441. if is_head or is_long_value or is_same_value:
  442. #不把连续表头分开
  443. if not is_head_last:
  444. head_list.append(i)
  445. if is_long_value or is_same_value:
  446. head_list.append(i+1)
  447. if is_head:
  448. for j in range(width):
  449. inner_table[i][j][1] = 1
  450. is_head_last = is_head
  451. head_list.append(height)
  452. #列表头
  453. for i in range(len(head_list)-1):
  454. head_begin = head_list[i]
  455. head_end = head_list[i+1]
  456. #最后一列不设置为列表头
  457. for i in range(width-1):
  458. is_head = False
  459. #predict is head or not with model
  460. temp_item = ""
  461. for j in range(head_begin,head_end):
  462. temp_item += inner_table[j][i][0]+"|"
  463. temp_item = re.sub(pad_pattern,"",temp_item)
  464. form_prob = getPredictor("form").predict(formEncoding(temp_item,expand=True),type="line")
  465. if form_prob is not None:
  466. if form_prob[0][1]>prob_min:
  467. is_head = True
  468. else:
  469. is_head = False
  470. if is_head:
  471. for j in range(head_begin,head_end):
  472. inner_table[j][i][1] = 2
  473. addPadding(inner_table, pad_row, pad_col)
  474. return inner_table,head_list
  475. #设置表头
  476. def setHead_withRule(inner_table,pattern,pat_value,count):
  477. height = len(inner_table)
  478. width = len(inner_table[0])
  479. head_list = []
  480. head_list.append(0)
  481. #行表头
  482. is_head_last = False
  483. for i in range(height):
  484. set_match = set()
  485. is_head = False
  486. is_long_value = False
  487. is_same_value = True
  488. same_value = inner_table[i][0][0]
  489. for j in range(width):
  490. if inner_table[i][j][0]!=same_value:
  491. is_same_value = False
  492. break
  493. for j in range(width):
  494. if re.search(pat_value,inner_table[i][j][0]) is not None:
  495. is_head = False
  496. break
  497. str_find = re.findall(pattern,inner_table[i][j][0])
  498. if len(str_find)>0:
  499. set_match.add(inner_table[i][j][0])
  500. if len(set_match)>=count:
  501. is_head = True
  502. if len(inner_table[i][0][0])>40:
  503. is_long_value = True
  504. if is_head or is_long_value or is_same_value:
  505. if not is_head_last:
  506. head_list.append(i)
  507. if is_head:
  508. for j in range(width):
  509. inner_table[i][j][1] = 1
  510. is_head_last = is_head
  511. head_list.append(height)
  512. #列表头
  513. for i in range(len(head_list)-1):
  514. head_begin = head_list[i]
  515. head_end = head_list[i+1]
  516. #最后一列不设置为列表头
  517. for i in range(width-1):
  518. set_match = set()
  519. is_head = False
  520. for j in range(head_begin,head_end):
  521. if re.search(pat_value,inner_table[j][i][0]) is not None:
  522. is_head = False
  523. break
  524. str_find = re.findall(pattern,inner_table[j][i][0])
  525. if len(str_find)>0:
  526. set_match.add(inner_table[j][i][0])
  527. if len(set_match)>=count:
  528. is_head = True
  529. if is_head:
  530. for j in range(head_begin,head_end):
  531. inner_table[j][i][1] = 2
  532. return inner_table,head_list
  533. #取得表格的处理方向
  534. def getDirect(inner_table,begin,end):
  535. '''
  536. column_head = set()
  537. row_head = set()
  538. widths = len(inner_table[0])
  539. for height in range(begin,end):
  540. for width in range(widths):
  541. if inner_table[height][width][1] ==1:
  542. row_head.add(height)
  543. if inner_table[height][width][1] ==2:
  544. column_head.add(width)
  545. company_pattern = re.compile("公司")
  546. if 0 in column_head and begin not in row_head:
  547. return "column"
  548. if 0 in column_head and begin in row_head:
  549. for height in range(begin,end):
  550. count = 0
  551. count_flag = True
  552. for width_index in range(width):
  553. if inner_table[height][width_index][1]==0:
  554. if re.search(company_pattern,inner_table[height][width_index][0]) is not None:
  555. count += 1
  556. else:
  557. count_flag = False
  558. if count_flag and count>=2:
  559. return "column"
  560. return "row"
  561. '''
  562. count_row_keys = 0
  563. count_column_keys = 0
  564. width = len(inner_table[0])
  565. if begin<end:
  566. for w in range(len(inner_table[begin])):
  567. if inner_table[begin][w][1]!=0:
  568. count_row_keys += 1
  569. for h in range(begin,end):
  570. if inner_table[h][0][1]!=0:
  571. count_column_keys += 1
  572. company_pattern = re.compile("有限(责任)?公司")
  573. for height in range(begin,end):
  574. count_set = set()
  575. count_flag = True
  576. for width_index in range(width):
  577. if inner_table[height][width_index][1]==0:
  578. if re.search(company_pattern,inner_table[height][width_index][0]) is not None:
  579. count_set.add(inner_table[height][width_index][0])
  580. else:
  581. count_flag = False
  582. if count_flag and len(count_set)>=2:
  583. return "column"
  584. if count_column_keys>count_row_keys:
  585. return "column"
  586. return "row"
  587. #根据表格处理方向生成句子,
  588. def getTableText(inner_table,head_list,key_direct=False):
  589. # packPattern = "(标包|[标包][号段名])"
  590. packPattern = "(标包|[标包][号段名]|((项目|物资|设备|场次|标段|标的|产品)(名称)))" # 2020/11/23 大网站规则,补充采购类包名
  591. rankPattern = "(排名|排序|名次|序号|评标结果|评审结果|是否中标|推荐意见)" # 2020/11/23 大网站规则,添加序号为排序
  592. entityPattern = "((候选|([中投]标|报价))(单位|公司|人|供应商))"
  593. moneyPattern = "([中投]标|报价)(金额|价)"
  594. height = len(inner_table)
  595. width = len(inner_table[0])
  596. text = ""
  597. for head_i in range(len(head_list)-1):
  598. head_begin = head_list[head_i]
  599. head_end = head_list[head_i+1]
  600. direct = getDirect(inner_table, head_begin, head_end)
  601. #若只有一行,则直接按行读取
  602. if head_end-head_begin==1:
  603. text_line = ""
  604. for i in range(head_begin,head_end):
  605. for w in range(len(inner_table[i])):
  606. if inner_table[i][w][1]==1:
  607. _punctuation = ":"
  608. else:
  609. _punctuation = "," #2021/12/15 统一为中文标点,避免 206893924 国际F座1108,1,009,197.49元
  610. if w>0:
  611. if inner_table[i][w][0]!= inner_table[i][w-1][0]:
  612. text_line += inner_table[i][w][0]+_punctuation
  613. else:
  614. text_line += inner_table[i][w][0]+_punctuation
  615. text_line = text_line+"。" if text_line!="" else text_line
  616. text += text_line
  617. else:
  618. #构建一个共现矩阵
  619. table_occurence = []
  620. for i in range(head_begin,head_end):
  621. line_oc = []
  622. for j in range(width):
  623. cell = inner_table[i][j]
  624. line_oc.append({"text":cell[0],"type":cell[1],"occu_count":0,"left_head":"","top_head":"","left_dis":0,"top_dis":0})
  625. table_occurence.append(line_oc)
  626. occu_height = len(table_occurence)
  627. occu_width = len(table_occurence[0]) if len(table_occurence)>0 else 0
  628. #为每个属性值寻找表头
  629. for i in range(occu_height):
  630. for j in range(occu_width):
  631. cell = table_occurence[i][j]
  632. #是属性值
  633. if cell["type"]==0 and cell["text"]!="":
  634. left_head = ""
  635. top_head = ""
  636. find_flag = False
  637. temp_head = ""
  638. for loop_i in range(1,i+1):
  639. if not key_direct:
  640. key_values = [1,2]
  641. else:
  642. key_values = [1]
  643. if table_occurence[i-loop_i][j]["type"] in key_values:
  644. if find_flag:
  645. if table_occurence[i-loop_i][j]["text"]!=temp_head:
  646. top_head = table_occurence[i-loop_i][j]["text"]+":"+top_head
  647. else:
  648. top_head = table_occurence[i-loop_i][j]["text"]+":"+top_head
  649. find_flag = True
  650. temp_head = table_occurence[i-loop_i][j]["text"]
  651. table_occurence[i-loop_i][j]["occu_count"] += 1
  652. else:
  653. #找到表头后遇到属性值就返回
  654. if find_flag:
  655. break
  656. cell["top_head"] += top_head
  657. find_flag = False
  658. temp_head = ""
  659. for loop_j in range(1,j+1):
  660. if not key_direct:
  661. key_values = [1,2]
  662. else:
  663. key_values = [2]
  664. if table_occurence[i][j-loop_j]["type"] in key_values:
  665. if find_flag:
  666. if table_occurence[i][j-loop_j]["text"]!=temp_head:
  667. left_head = table_occurence[i][j-loop_j]["text"]+":"+left_head
  668. else:
  669. left_head = table_occurence[i][j-loop_j]["text"]+":"+left_head
  670. find_flag = True
  671. temp_head = table_occurence[i][j-loop_j]["text"]
  672. table_occurence[i][j-loop_j]["occu_count"] += 1
  673. else:
  674. if find_flag:
  675. break
  676. cell["left_head"] += left_head
  677. if direct=="row":
  678. for i in range(occu_height):
  679. pack_text = ""
  680. rank_text = ""
  681. entity_text = ""
  682. text_line = ""
  683. money_text = ""
  684. #在同一句话中重复的可以去掉
  685. text_set = set()
  686. for j in range(width):
  687. cell = table_occurence[i][j]
  688. if cell["type"]==0 or (cell["type"]==1 and cell["occu_count"]==0):
  689. cell = table_occurence[i][j]
  690. head = (cell["top_head"]+":") if len(cell["top_head"])>0 else ""
  691. if re.search("单报标限总]价|金额|成交报?价|报价", head):
  692. head = cell["left_head"] + head
  693. else:
  694. head += cell["left_head"]
  695. if str(head+cell["text"]) in text_set:
  696. continue
  697. if re.search(packPattern,head) is not None:
  698. pack_text += head+cell["text"]+","
  699. elif re.search(rankPattern,head) is not None: # 2020/11/23 大网站规则发现问题,if 改elif
  700. #排名替换为同一种表达
  701. rank_text += head+cell["text"]+","
  702. #print(rank_text)
  703. elif re.search(entityPattern,head) is not None:
  704. entity_text += head+cell["text"]+","
  705. #print(entity_text)
  706. else:
  707. if re.search(moneyPattern,head) is not None and entity_text!="":
  708. money_text += head+cell["text"]+","
  709. else:
  710. text_line += head+cell["text"]+","
  711. text_set.add(str(head+cell["text"]))
  712. text += pack_text+rank_text+entity_text+money_text+text_line
  713. text = text[:-1]+"。" if len(text)>0 else text
  714. else:
  715. for j in range(occu_width):
  716. pack_text = ""
  717. rank_text = ""
  718. entity_text = ""
  719. text_line = ""
  720. text_set = set()
  721. for i in range(occu_height):
  722. cell = table_occurence[i][j]
  723. if cell["type"]==0 or (cell["type"]==1 and cell["occu_count"]==0):
  724. cell = table_occurence[i][j]
  725. head = (cell["left_head"]+"") if len(cell["left_head"])>0 else ""
  726. if re.search("单报标限总]价|金额|成交报?价|报价", head):
  727. head = cell["top_head"] + head
  728. else:
  729. head += cell["top_head"]
  730. if str(head+cell["text"]) in text_set:
  731. continue
  732. if re.search(packPattern,head) is not None:
  733. pack_text += head+cell["text"]+","
  734. elif re.search(rankPattern,head) is not None: # 2020/11/23 大网站规则发现问题,if 改elif
  735. #排名替换为同一种表达
  736. rank_text += head+cell["text"]+","
  737. #print(rank_text)
  738. elif re.search(entityPattern,head) is not None and \
  739. re.search('业绩|资格|条件',head)==None and re.search('业绩',cell["text"])==None : #2021/10/19 解决包含业绩的行调到前面问题
  740. entity_text += head+cell["text"]+","
  741. #print(entity_text)
  742. else:
  743. text_line += head+cell["text"]+","
  744. text_set.add(str(head+cell["text"]))
  745. text += pack_text+rank_text+entity_text+text_line
  746. text = text[:-1]+"。" if len(text)>0 else text
  747. # if direct=="row":
  748. # for i in range(head_begin,head_end):
  749. # pack_text = ""
  750. # rank_text = ""
  751. # entity_text = ""
  752. # text_line = ""
  753. # #在同一句话中重复的可以去掉
  754. # text_set = set()
  755. # for j in range(width):
  756. # cell = inner_table[i][j]
  757. # #是属性值
  758. # if cell[1]==0 and cell[0]!="":
  759. # head = ""
  760. #
  761. # find_flag = False
  762. # temp_head = ""
  763. # for loop_i in range(0,i+1-head_begin):
  764. # if not key_direct:
  765. # key_values = [1,2]
  766. # else:
  767. # key_values = [1]
  768. # if inner_table[i-loop_i][j][1] in key_values:
  769. # if find_flag:
  770. # if inner_table[i-loop_i][j][0]!=temp_head:
  771. # head = inner_table[i-loop_i][j][0]+":"+head
  772. # else:
  773. # head = inner_table[i-loop_i][j][0]+":"+head
  774. # find_flag = True
  775. # temp_head = inner_table[i-loop_i][j][0]
  776. # else:
  777. # #找到表头后遇到属性值就返回
  778. # if find_flag:
  779. # break
  780. #
  781. # find_flag = False
  782. # temp_head = ""
  783. #
  784. #
  785. #
  786. # for loop_j in range(1,j+1):
  787. # if not key_direct:
  788. # key_values = [1,2]
  789. # else:
  790. # key_values = [2]
  791. # if inner_table[i][j-loop_j][1] in key_values:
  792. # if find_flag:
  793. # if inner_table[i][j-loop_j][0]!=temp_head:
  794. # head = inner_table[i][j-loop_j][0]+":"+head
  795. # else:
  796. # head = inner_table[i][j-loop_j][0]+":"+head
  797. # find_flag = True
  798. # temp_head = inner_table[i][j-loop_j][0]
  799. # else:
  800. # if find_flag:
  801. # break
  802. #
  803. # if str(head+inner_table[i][j][0]) in text_set:
  804. # continue
  805. # if re.search(packPattern,head) is not None:
  806. # pack_text += head+inner_table[i][j][0]+","
  807. # elif re.search(rankPattern,head) is not None: # 2020/11/23 大网站规则发现问题,if 改elif
  808. # #排名替换为同一种表达
  809. # rank_text += head+inner_table[i][j][0]+","
  810. # #print(rank_text)
  811. # elif re.search(entityPattern,head) is not None:
  812. # entity_text += head+inner_table[i][j][0]+","
  813. # #print(entity_text)
  814. # else:
  815. # text_line += head+inner_table[i][j][0]+","
  816. # text_set.add(str(head+inner_table[i][j][0]))
  817. # text += pack_text+rank_text+entity_text+text_line
  818. # text = text[:-1]+"。" if len(text)>0 else text
  819. # else:
  820. # for j in range(width):
  821. #
  822. # rank_text = ""
  823. # entity_text = ""
  824. # text_line = ""
  825. # text_set = set()
  826. # for i in range(head_begin,head_end):
  827. # cell = inner_table[i][j]
  828. # #是属性值
  829. # if cell[1]==0 and cell[0]!="":
  830. # find_flag = False
  831. # head = ""
  832. # temp_head = ""
  833. #
  834. # for loop_j in range(1,j+1):
  835. # if not key_direct:
  836. # key_values = [1,2]
  837. # else:
  838. # key_values = [2]
  839. # if inner_table[i][j-loop_j][1] in key_values:
  840. # if find_flag:
  841. # if inner_table[i][j-loop_j][0]!=temp_head:
  842. # head = inner_table[i][j-loop_j][0]+":"+head
  843. # else:
  844. # head = inner_table[i][j-loop_j][0]+":"+head
  845. # find_flag = True
  846. # temp_head = inner_table[i][j-loop_j][0]
  847. # else:
  848. # if find_flag:
  849. # break
  850. # find_flag = False
  851. # temp_head = ""
  852. # for loop_i in range(0,i+1-head_begin):
  853. # if not key_direct:
  854. # key_values = [1,2]
  855. # else:
  856. # key_values = [1]
  857. # if inner_table[i-loop_i][j][1] in key_values:
  858. # if find_flag:
  859. # if inner_table[i-loop_i][j][0]!=temp_head:
  860. # head = inner_table[i-loop_i][j][0]+":"+head
  861. # else:
  862. # head = inner_table[i-loop_i][j][0]+":"+head
  863. # find_flag = True
  864. # temp_head = inner_table[i-loop_i][j][0]
  865. # else:
  866. # if find_flag:
  867. # break
  868. # if str(head+inner_table[i][j][0]) in text_set:
  869. # continue
  870. # if re.search(rankPattern,head) is not None:
  871. # rank_text += head+inner_table[i][j][0]+","
  872. # #print(rank_text)
  873. # elif re.search(entityPattern,head) is not None:
  874. # entity_text += head+inner_table[i][j][0]+","
  875. # #print(entity_text)
  876. # else:
  877. # text_line += head+inner_table[i][j][0]+","
  878. # text_set.add(str(head+inner_table[i][j][0]))
  879. # text += rank_text+entity_text+text_line
  880. # text = text[:-1]+"。" if len(text)>0 else text
  881. return text
  882. def removeFix(inner_table,fix_value="~~"):
  883. height = len(inner_table)
  884. width = len(inner_table[0])
  885. for h in range(height):
  886. for w in range(width):
  887. if inner_table[h][w][0]==fix_value:
  888. inner_table[h][w][0] = ""
  889. def trunTable(tbody):
  890. fixSpan(tbody)
  891. inner_table = getTable(tbody)
  892. inner_table = fixTable(inner_table)
  893. if len(inner_table)>0 and len(inner_table[0])>0:
  894. #inner_table,head_list = setHead_withRule(inner_table,pat_head,pat_value,3)
  895. #inner_table,head_list = setHead_inline(inner_table)
  896. # inner_table,head_list = setHead_initem(inner_table,pat_head)
  897. inner_table,head_list = setHead_incontext(inner_table,pat_head)
  898. # print(inner_table)
  899. # for begin in range(len(head_list[:-1])):
  900. # for item in inner_table[head_list[begin]:head_list[begin+1]]:
  901. # print(item)
  902. # print("====")
  903. removeFix(inner_table)
  904. # print("----")
  905. # print(head_list)
  906. # for item in inner_table:
  907. # print(item)
  908. tbody.string = getTableText(inner_table,head_list)
  909. #print(tbody.string)
  910. tbody.name = "turntable"
  911. return inner_table
  912. return None
  913. pat_head = re.compile('^(名称|序号|项目|标项|工程|品目[一二三四1234]|第[一二三四1234](标段|名|候选人|中标)|包段|标包|分包|包号|货物|单位|数量|价格|报价|金额|总价|单价|[招投中]标|供应商|候选|编号|得分|评委|评分|名次|排名|排序|科室|方式|工期|时间|产品|开始|结束|联系|日期|面积|姓名|证号|备注|级别|地[点址]|类型|代理|制造|企业资质|质量目标|工期目标)$')
  914. #pat_head = re.compile('(名称|序号|项目|工程|品目[一二三四1234]|第[一二三四1234](标段|候选人|中标)|包段|包号|货物|单位|数量|价格|报价|金额|总价|单价|[招投中]标|供应商|候选|编号|得分|评委|评分|名次|排名|排序|科室|方式|工期|时间|产品|开始|结束|联系|日期|面积|姓名|证号|备注|级别|地[点址]|类型|代理)')
  915. pat_value = re.compile("(\d{2,}.\d{1}|\d+年\d+月|\d{8,}|\d{3,}-\d{6,}|有限[责任]*公司|^\d+$)")
  916. list_innerTable = []
  917. tbodies = soup.find_all('table')
  918. # 遍历表格中的每个tbody
  919. #逆序处理嵌套表格
  920. for tbody_index in range(1,len(tbodies)+1):
  921. tbody = tbodies[len(tbodies)-tbody_index]
  922. inner_table = trunTable(tbody)
  923. list_innerTable.append(inner_table)
  924. tbodies = soup.find_all('tbody')
  925. # 遍历表格中的每个tbody
  926. #逆序处理嵌套表格
  927. for tbody_index in range(1,len(tbodies)+1):
  928. tbody = tbodies[len(tbodies)-tbody_index]
  929. inner_table = trunTable(tbody)
  930. list_innerTable.append(inner_table)
  931. return soup
  932. # return list_innerTable
  933. #数据清洗
  934. def segment(soup,final=True):
  935. # print("==")
  936. # print(soup)
  937. # print("====")
  938. #segList = ["tr","div","h1", "h2", "h3", "h4", "h5", "h6", "header"]
  939. subspaceList = ["td",'a',"span","p"]
  940. if soup.name in subspaceList:
  941. #判断有值叶子节点数
  942. _count = 0
  943. for child in soup.find_all(recursive=True):
  944. if child.get_text().strip()!="" and len(child.find_all())==0:
  945. _count += 1
  946. if _count<=1:
  947. text = soup.get_text()
  948. # 2020/11/24 大网站规则添加
  949. if 'title' in soup.attrs:
  950. if '...' in soup.get_text() and soup.get_text().strip()[:-3] in soup.attrs['title']:
  951. text = soup.attrs['title']
  952. _list = []
  953. for x in re.split("\s+",text):
  954. if x.strip()!="":
  955. _list.append(len(x))
  956. if len(_list)>0:
  957. _minLength = min(_list)
  958. if _minLength>2:
  959. _substr = ","
  960. else:
  961. _substr = ""
  962. else:
  963. _substr = ""
  964. text = text.replace("\r\n",",").replace("\n",",")
  965. text = re.sub("\s+",_substr,text)
  966. # text = re.sub("\s+","##space##",text)
  967. return text
  968. segList = ["title"]
  969. commaList = ["div","br","td","p"]
  970. #commaList = []
  971. spaceList = ["span"]
  972. tbodies = soup.find_all('tbody')
  973. if len(tbodies) == 0:
  974. tbodies = soup.find_all('table')
  975. # 递归遍历所有节点,插入符号
  976. for child in soup.find_all(recursive=True):
  977. if child.name in segList:
  978. child.insert_after("。")
  979. if child.name in commaList:
  980. child.insert_after(",")
  981. # if child.name in subspaceList:
  982. # child.insert_before("#subs"+str(child.name)+"#")
  983. # child.insert_after("#sube"+str(child.name)+"#")
  984. # if child.name in spaceList:
  985. # child.insert_after(" ")
  986. text = str(soup.get_text())
  987. #替换英文冒号为中文冒号
  988. text = re.sub("(?<=[\u4e00-\u9fa5]):|:(?=[\u4e00-\u9fa5])",":",text)
  989. #替换为中文逗号
  990. text = re.sub("(?<=[\u4e00-\u9fa5]),|,(?=[\u4e00-\u9fa5])",",",text)
  991. #替换为中文分号
  992. text = re.sub("(?<=[\u4e00-\u9fa5]);|;(?=[\u4e00-\u9fa5])",";",text)
  993. # 感叹号替换为中文句号
  994. text = re.sub("(?<=[\u4e00-\u9fa5])[!!]|[!!](?=[\u4e00-\u9fa5])","。",text)
  995. #替换"?"为 " " ,update:2021/7/20
  996. text = re.sub("?"," ",text)
  997. #替换"""为"“",否则导入deepdive出错
  998. text = text.replace('"',"“").replace("\r","").replace("\n",",")
  999. # print('==1',text)
  1000. # text = re.sub("\s{4,}",",",text)
  1001. # 解决公告中的" "空格替换问题
  1002. if re.search("\s{4,}",text):
  1003. _text = ""
  1004. for _sent in re.split("。+",text):
  1005. for _sent2 in re.split(',+',_sent):
  1006. for _sent3 in re.split(":+",_sent2):
  1007. for _t in re.split("\s{4,}",_sent3):
  1008. if len(_t)<3:
  1009. _text += _t
  1010. else:
  1011. _text += ","+_t
  1012. _text += ":"
  1013. _text = _text[:-1]
  1014. _text += ","
  1015. _text = _text[:-1]
  1016. _text += "。"
  1017. _text = _text[:-1]
  1018. text = _text
  1019. # print('==2',text)
  1020. #替换标点
  1021. #替换连续的标点
  1022. if final:
  1023. text = re.sub("##space##"," ",text)
  1024. punc_pattern = "(?P<del>[。,;::,\s]+)"
  1025. list_punc = re.findall(punc_pattern,text)
  1026. list_punc.sort(key=lambda x:len(x),reverse=True)
  1027. for punc_del in list_punc:
  1028. if len(punc_del)>1:
  1029. if len(punc_del.strip())>0:
  1030. if ":" in punc_del.strip():
  1031. text = re.sub(punc_del,":",text)
  1032. else:
  1033. text = re.sub(punc_del,punc_del.strip()[0],text) #2021/12/09 修正由于某些标签后插入符号把原来符号替换
  1034. else:
  1035. text = re.sub(punc_del,"",text)
  1036. #将连续的中文句号替换为一个
  1037. text_split = text.split("。")
  1038. text_split = [x for x in text_split if len(x)>0]
  1039. text = "。".join(text_split)
  1040. # #删除标签中的所有空格
  1041. # for subs in subspaceList:
  1042. # patten = "#subs"+str(subs)+"#(.*?)#sube"+str(subs)+"#"
  1043. # while(True):
  1044. # oneMatch = re.search(re.compile(patten),text)
  1045. # if oneMatch is not None:
  1046. # _match = oneMatch.group(1)
  1047. # text = text.replace("#subs"+str(subs)+"#"+_match+"#sube"+str(subs)+"#",_match)
  1048. # else:
  1049. # break
  1050. # text过大报错
  1051. LOOP_LEN = 10000
  1052. LOOP_BEGIN = 0
  1053. _text = ""
  1054. if len(text)<10000000:
  1055. while(LOOP_BEGIN<len(text)):
  1056. _text += re.sub(")",")",re.sub("(","(",re.sub("\s+","",text[LOOP_BEGIN:LOOP_BEGIN+LOOP_LEN])))
  1057. LOOP_BEGIN += LOOP_LEN
  1058. text = _text
  1059. return text
  1060. '''
  1061. #数据清洗
  1062. def segment(soup):
  1063. segList = ["title"]
  1064. commaList = ["p","div","h1", "h2", "h3", "h4", "h5", "h6", "header", "dl", "ul", "label"]
  1065. spaceList = ["span"]
  1066. tbodies = soup.find_all('tbody')
  1067. if len(tbodies) == 0:
  1068. tbodies = soup.find_all('table')
  1069. # 递归遍历所有节点,插入符号
  1070. for child in soup.find_all(recursive=True):
  1071. if child.name == 'br':
  1072. child.insert_before(',')
  1073. child_text = re.sub('\s', '', child.get_text())
  1074. if child_text == '' or child_text[-1] in ['。',',',':',';']:
  1075. continue
  1076. if child.name in segList:
  1077. child.insert_after("。")
  1078. if child.name in commaList:
  1079. if len(child_text)>3 and len(child_text) <50: # 先判断是否字数少于50,成立加逗号,否则加句号
  1080. child.insert_after(",")
  1081. elif len(child_text) >=50:
  1082. child.insert_after("。")
  1083. #if child.name in spaceList:
  1084. #child.insert_after(" ")
  1085. text = str(soup.get_text())
  1086. text = re.sub("\s{5,}",",",text)
  1087. text = text.replace('"',"“").replace("\r","").replace("\n",",")
  1088. #替换"""为"“",否则导入deepdive出错
  1089. text = text.replace('"',"“")
  1090. #text = text.replace('"',"“").replace("\r","").replace("\n","")
  1091. #删除所有空格
  1092. text = re.sub("\s+","#nbsp#",text)
  1093. text_list = text.split('#nbsp#')
  1094. new_text = ''
  1095. for i in range(len(text_list)-1):
  1096. if text_list[i] == '' or text_list[i][-1] in [',','。',';',':']:
  1097. new_text += text_list[i]
  1098. elif re.findall('([一二三四五六七八九]、)', text_list[i+1][:4]) != []:
  1099. new_text += text_list[i] + '。'
  1100. elif re.findall('([0-9]、)', text_list[i+1][:4]) != []:
  1101. new_text += text_list[i] + ';'
  1102. elif text_list[i].isdigit() and text_list[i+1].isdigit():
  1103. new_text += text_list[i] + ' '
  1104. elif text_list[i][-1] in ['-',':','(',')','/','(',')','——','年','月','日','时','分','¥'] or text_list[i+1][0] in ['-',':','(',')','/','(',')','——','年','月','日','时','分','元','万元']:
  1105. new_text += text_list[i]
  1106. elif len(text_list[i]) >= 3 and len(text_list[i+1]) >= 3:
  1107. new_text += text_list[i] + ','
  1108. else:
  1109. new_text += text_list[i]
  1110. new_text += text_list[-1]
  1111. text = new_text
  1112. #替换英文冒号为中文冒号
  1113. text = re.sub("(?<=[\u4e00-\u9fa5]):|:(?=[\u4e00-\u9fa5])",":",text)
  1114. #替换为中文逗号
  1115. text = re.sub("(?<=[\u4e00-\u9fa5]),|,(?=[\u4e00-\u9fa5])",",",text)
  1116. #替换为中文分号
  1117. text = re.sub("(?<=[\u4e00-\u9fa5]);|;(?=[\u4e00-\u9fa5])",";",text)
  1118. #替换标点
  1119. while(True):
  1120. #替换连续的标点
  1121. punc = re.search(",(?P<punc>:|。|,|;)\s*",text)
  1122. if punc is not None:
  1123. text = re.sub(","+punc.group("punc")+"\s*",punc.group("punc"),text)
  1124. punc = re.search("(?P<punc>:|。|,|;)\s*,",text)
  1125. if punc is not None:
  1126. text = re.sub(punc.group("punc")+"\s*,",punc.group("punc"),text)
  1127. else:
  1128. #替换标点之后的空格
  1129. punc = re.search("(?P<punc>:|。|,|;)\s+",text)
  1130. if punc is not None:
  1131. text = re.sub(punc.group("punc")+"\s+",punc.group("punc"),text)
  1132. else:
  1133. break
  1134. #将连续的中文句号替换为一个
  1135. text_split = text.split("。")
  1136. text_split = [x for x in text_split if len(x)>0]
  1137. text = "。".join(text_split)
  1138. #替换中文括号为英文括号
  1139. text = re.sub("(","(",text)
  1140. text = re.sub(")",")",text)
  1141. return text
  1142. '''
  1143. #连续实体合并(弃用)
  1144. def union_ner(list_ner):
  1145. result_list = []
  1146. union_index = []
  1147. union_index_set = set()
  1148. for i in range(len(list_ner)-1):
  1149. if len(set([str(list_ner[i][2]),str(list_ner[i+1][2])])&set(["org","company"]))==2:
  1150. if list_ner[i][1]-list_ner[i+1][0]==1:
  1151. union_index_set.add(i)
  1152. union_index_set.add(i+1)
  1153. union_index.append((i,i+1))
  1154. for i in range(len(list_ner)):
  1155. if i not in union_index_set:
  1156. result_list.append(list_ner[i])
  1157. for item in union_index:
  1158. #print(str(list_ner[item[0]][3])+str(list_ner[item[1]][3]))
  1159. result_list.append((list_ner[item[0]][0],list_ner[item[1]][1],'company',str(list_ner[item[0]][3])+str(list_ner[item[1]][3])))
  1160. return result_list
  1161. # def get_preprocessed(articles,useselffool=False):
  1162. # '''
  1163. # @summary:预处理步骤,NLP处理、实体识别
  1164. # @param:
  1165. # articles:待处理的文章list [[id,source,jointime,doc_id,title]]
  1166. # @return:list of articles,list of each article of sentences,list of each article of entitys
  1167. # '''
  1168. # list_articles = []
  1169. # list_sentences = []
  1170. # list_entitys = []
  1171. # cost_time = dict()
  1172. # for article in articles:
  1173. # list_sentences_temp = []
  1174. # list_entitys_temp = []
  1175. # doc_id = article[0]
  1176. # sourceContent = article[1]
  1177. # _send_doc_id = article[3]
  1178. # _title = article[4]
  1179. # #表格处理
  1180. # key_preprocess = "tableToText"
  1181. # start_time = time.time()
  1182. # article_processed = segment(tableToText(BeautifulSoup(sourceContent,"lxml")))
  1183. #
  1184. # # log(article_processed)
  1185. #
  1186. # if key_preprocess not in cost_time:
  1187. # cost_time[key_preprocess] = 0
  1188. # cost_time[key_preprocess] += time.time()-start_time
  1189. #
  1190. # #article_processed = article[1]
  1191. # list_articles.append(Article(doc_id,article_processed,sourceContent,_send_doc_id,_title))
  1192. # #nlp处理
  1193. # if article_processed is not None and len(article_processed)!=0:
  1194. # split_patten = "。"
  1195. # sentences = []
  1196. # _begin = 0
  1197. # for _iter in re.finditer(split_patten,article_processed):
  1198. # sentences.append(article_processed[_begin:_iter.span()[1]])
  1199. # _begin = _iter.span()[1]
  1200. # sentences.append(article_processed[_begin:])
  1201. #
  1202. # lemmas = []
  1203. # doc_offsets = []
  1204. # dep_types = []
  1205. # dep_tokens = []
  1206. #
  1207. # time1 = time.time()
  1208. #
  1209. # '''
  1210. # tokens_all = fool.cut(sentences)
  1211. # #pos_all = fool.LEXICAL_ANALYSER.pos(tokens_all)
  1212. # #ner_tag_all = fool.LEXICAL_ANALYSER.ner_labels(sentences,tokens_all)
  1213. # ner_entitys_all = fool.ner(sentences)
  1214. # '''
  1215. # #限流执行
  1216. # key_nerToken = "nerToken"
  1217. # start_time = time.time()
  1218. # tokens_all,ner_entitys_all = getTokensAndNers(sentences,useselffool=useselffool)
  1219. # if key_nerToken not in cost_time:
  1220. # cost_time[key_nerToken] = 0
  1221. # cost_time[key_nerToken] += time.time()-start_time
  1222. #
  1223. #
  1224. # for sentence_index in range(len(sentences)):
  1225. #
  1226. #
  1227. #
  1228. # list_sentence_entitys = []
  1229. # sentence_text = sentences[sentence_index]
  1230. # tokens = tokens_all[sentence_index]
  1231. #
  1232. # list_tokenbegin = []
  1233. # begin = 0
  1234. # for i in range(0,len(tokens)):
  1235. # list_tokenbegin.append(begin)
  1236. # begin += len(str(tokens[i]))
  1237. # list_tokenbegin.append(begin+1)
  1238. # #pos_tag = pos_all[sentence_index]
  1239. # pos_tag = ""
  1240. #
  1241. # ner_entitys = ner_entitys_all[sentence_index]
  1242. #
  1243. # list_sentences_temp.append(Sentences(doc_id=doc_id,sentence_index=sentence_index,sentence_text=sentence_text,tokens=tokens,pos_tags=pos_tag,ner_tags=ner_entitys))
  1244. #
  1245. # #识别package
  1246. #
  1247. #
  1248. # #识别实体
  1249. # for ner_entity in ner_entitys:
  1250. # begin_index_temp = ner_entity[0]
  1251. # end_index_temp = ner_entity[1]
  1252. # entity_type = ner_entity[2]
  1253. # entity_text = ner_entity[3]
  1254. #
  1255. # for j in range(len(list_tokenbegin)):
  1256. # if list_tokenbegin[j]==begin_index_temp:
  1257. # begin_index = j
  1258. # break
  1259. # elif list_tokenbegin[j]>begin_index_temp:
  1260. # begin_index = j-1
  1261. # break
  1262. # begin_index_temp += len(str(entity_text))
  1263. # for j in range(begin_index,len(list_tokenbegin)):
  1264. # if list_tokenbegin[j]>=begin_index_temp:
  1265. # end_index = j-1
  1266. # break
  1267. # entity_id = "%s_%d_%d_%d"%(doc_id,sentence_index,begin_index,end_index)
  1268. #
  1269. # #去掉标点符号
  1270. # entity_text = re.sub("[,,。:]","",entity_text)
  1271. # list_sentence_entitys.append(Entity(doc_id,entity_id,entity_text,entity_type,sentence_index,begin_index,end_index,ner_entity[0],ner_entity[1]-1))
  1272. #
  1273. #
  1274. # #使用正则识别金额
  1275. # entity_type = "money"
  1276. #
  1277. # #money_patten_str = "(([1-9][\d,,]*(?:\.\d+)?[百千万亿]?[\(\)()元整]+)|([零壹贰叁肆伍陆柒捌玖拾佰仟萬億十百千万亿元角分]{3,})|(?:[¥¥]+,?|报价|标价)[(\(]?([万])?元?[)\)]?[::]?.{,7}?([1-9][\d,,]*(?:\.\d+)?(?:,?)[百千万亿]?)|([1-9][\d,,]*(?:\.\d+)?(?:,?)[百千万亿]?)[\((]?([万元]{1,2}))*"
  1278. #
  1279. # list_money_pattern = {"cn":"(()()([零壹贰叁肆伍陆柒捌玖拾佰仟萬億十百千万亿元角分]{3,})())*",
  1280. # "key_word":"((?:[¥¥]+,?|[报标限]价|金额)(?:[(\(]?\s*([万元]*)\s*[)\)]?)\s*[::]?(\s*[^壹贰叁肆伍陆柒捌玖拾佰仟萬億分]{,7}?)([0-9][\d,,]*(?:\.\d+)?(?:,?)[百千万亿元]*)())*",
  1281. # "front_m":"((?:[(\(]?\s*([万元]+)\s*[)\)])\s*[::]?(\s*[^壹贰叁肆伍陆柒捌玖拾佰仟萬億分]{,7}?)([0-9][\d,,]*(?:\.\d+)?(?:,?)[百千万亿元]*)())*",
  1282. # "behind_m":"(()()([0-9][\d,,]*(?:\.\d+)?(?:,?)[百千万亿]*)[\((]?([万元]+)[\))]?)*"}
  1283. #
  1284. # set_begin = set()
  1285. # for pattern_key in list_money_pattern.keys():
  1286. # pattern = re.compile(list_money_pattern[pattern_key])
  1287. # all_match = re.findall(pattern, sentence_text)
  1288. # index = 0
  1289. # for i in range(len(all_match)):
  1290. # if len(all_match[i][0])>0:
  1291. # # print("===",all_match[i])
  1292. # #print(all_match[i][0])
  1293. # unit = ""
  1294. # entity_text = all_match[i][3]
  1295. # if pattern_key in ["key_word","front_m"]:
  1296. # unit = all_match[i][1]
  1297. # else:
  1298. # unit = all_match[i][4]
  1299. # if entity_text.find("元")>=0:
  1300. # unit = ""
  1301. #
  1302. # index += len(all_match[i][0])-len(entity_text)-len(all_match[i][4])#-len(all_match[i][1])-len(all_match[i][2])#整个提出来的作为实体->数字部分作为整体,否则会丢失特征
  1303. #
  1304. # begin_index_temp = index
  1305. # for j in range(len(list_tokenbegin)):
  1306. # if list_tokenbegin[j]==index:
  1307. # begin_index = j
  1308. # break
  1309. # elif list_tokenbegin[j]>index:
  1310. # begin_index = j-1
  1311. # break
  1312. # index += len(str(entity_text))+len(all_match[i][4])#+len(all_match[i][2])+len(all_match[i][1])#整个提出来的作为实体
  1313. # end_index_temp = index
  1314. # #index += len(str(all_match[i][0]))
  1315. # for j in range(begin_index,len(list_tokenbegin)):
  1316. # if list_tokenbegin[j]>=index:
  1317. # end_index = j-1
  1318. # break
  1319. # entity_id = "%s_%d_%d_%d"%(doc_id,sentence_index,begin_index,end_index)
  1320. #
  1321. #
  1322. # entity_text = re.sub("[^0-9.零壹贰叁肆伍陆柒捌玖拾佰仟萬億十百千万亿元角分]","",entity_text)
  1323. # if len(unit)>0:
  1324. # entity_text = str(getUnifyMoney(entity_text)*getMultipleFactor(unit[0]))
  1325. # else:
  1326. # entity_text = str(getUnifyMoney(entity_text))
  1327. #
  1328. # _exists = False
  1329. # for item in list_sentence_entitys:
  1330. # if item.entity_id==entity_id and item.entity_type==entity_type:
  1331. # _exists = True
  1332. # if not _exists:
  1333. # if float(entity_text)>10:
  1334. # list_sentence_entitys.append(Entity(doc_id,entity_id,entity_text,entity_type,sentence_index,begin_index,end_index,begin_index_temp,end_index_temp))
  1335. #
  1336. # else:
  1337. # index += 1
  1338. #
  1339. # list_sentence_entitys.sort(key=lambda x:x.begin_index)
  1340. # list_entitys_temp = list_entitys_temp+list_sentence_entitys
  1341. # list_sentences.append(list_sentences_temp)
  1342. # list_entitys.append(list_entitys_temp)
  1343. # return list_articles,list_sentences,list_entitys,cost_time
  1344. def get_preprocessed(articles,useselffool=False):
  1345. '''
  1346. @summary:预处理步骤,NLP处理、实体识别
  1347. @param:
  1348. articles:待处理的文章list [[id,source,jointime,doc_id,title]]
  1349. @return:list of articles,list of each article of sentences,list of each article of entitys
  1350. '''
  1351. cost_time = dict()
  1352. list_articles = get_preprocessed_article(articles,cost_time)
  1353. list_sentences = get_preprocessed_sentences(list_articles,True,cost_time)
  1354. list_entitys = get_preprocessed_entitys(list_sentences,True,cost_time)
  1355. calibrateEnterprise(list_articles,list_sentences,list_entitys)
  1356. return list_articles,list_sentences,list_entitys,cost_time
  1357. def get_preprocessed_article(articles,cost_time = dict(),useselffool=True):
  1358. '''
  1359. :param articles: 待处理的article source html
  1360. :param useselffool: 是否使用selffool
  1361. :return: list_articles
  1362. '''
  1363. list_articles = []
  1364. for article in articles:
  1365. doc_id = article[0]
  1366. sourceContent = article[1]
  1367. sourceContent = re.sub("<html>|</html>|<body>|</body>","",sourceContent)
  1368. _send_doc_id = article[3]
  1369. _title = article[4]
  1370. page_time = article[5]
  1371. #表格处理
  1372. key_preprocess = "tableToText"
  1373. start_time = time.time()
  1374. article_processed = segment(tableToText(BeautifulSoup(sourceContent,"lxml")))
  1375. article_processed = article_processed.replace('.','.') # 2021/12/01 修正OCR识别PDF小数点错误问题
  1376. article_processed = article_processed.replace('报价限价', '招标限价') #2021/12/17 由于报价限价预测为中投标金额所以修改
  1377. article_processed = article_processed.replace('成交工程价款', '成交工程价') # 2021/12/21 修正为中标价
  1378. # 提取bidway
  1379. list_bidway = extract_bidway(article_processed, _title)
  1380. if list_bidway:
  1381. bidway = list_bidway[0].get("body")
  1382. # bidway名称统一规范
  1383. bidway = bidway_integrate(bidway)
  1384. else:
  1385. bidway = ""
  1386. # 修正被","逗号分隔的时间
  1387. repair_time = re.compile("[12]\d,?\d,?\d,?[-—-―/年],?[0-1]?\d,?[-—-―/月],?[0-3]?\d,?[日号]?,?(?:上午|下午)?,?[0-2]?\d,?:,?[0-6]\d,?:,?[0-6]\d|"
  1388. "[12]\d,?\d,?\d,?[-—-―/年],?[0-1]?\d,?[-—-―/月],?[0-3]?\d,?[日号]?,?(?:上午|下午)?,?[0-2]?\d,?[:时点],?[0-6]\d分?|"
  1389. "[12]\d,?\d,?\d,?[-—-―/年],?[0-1]?\d,?[-—-―/月],?[0-3]?\d,?[日号]?,?(?:上午|下午)?,?[0-2]?\d,?[时点]|"
  1390. "[12]\d,?\d,?\d,?[-—-―/年],?[0-1]?\d,?[-—-―/月],?[0-3]?\d,?[日号]|"
  1391. "[0-2]?\d,?:,?[0-6]\d,?:,?[0-6]\d"
  1392. )
  1393. for _time in set(re.findall(repair_time,article_processed)):
  1394. if re.search(",",_time):
  1395. _time2 = re.sub(",", "", _time)
  1396. item = re.search("[12]\d{3}[-—-―/][0-1]?\d[-—-―/][0-3]\d(?=\d)", _time2)
  1397. if item:
  1398. _time2 = _time2.replace(item.group(),item.group() + " ")
  1399. article_processed = article_processed.replace(_time, _time2)
  1400. else:
  1401. item = re.search("[12]\d{3}[-—-―/][0-1]?\d[-—-―/][0-3]\d(?=\d)", _time)
  1402. if item:
  1403. _time2 = _time.replace(item.group(),item.group() + " ")
  1404. article_processed = article_processed.replace(_time, _time2)
  1405. # print('re_rtime',re.findall(repair_time,article_processed))
  1406. # log(article_processed)
  1407. if key_preprocess not in cost_time:
  1408. cost_time[key_preprocess] = 0
  1409. cost_time[key_preprocess] += round(time.time()-start_time,2)
  1410. #article_processed = article[1]
  1411. _article = Article(doc_id,article_processed,sourceContent,_send_doc_id,_title,
  1412. bidway=bidway)
  1413. _article.fingerprint = getFingerprint(_title+sourceContent)
  1414. _article.page_time = page_time
  1415. list_articles.append(_article)
  1416. return list_articles
  1417. def get_preprocessed_sentences(list_articles,useselffool=True,cost_time=dict()):
  1418. '''
  1419. :param list_articles: 经过预处理的article text
  1420. :return: list_sentences
  1421. '''
  1422. list_sentences = []
  1423. for article in list_articles:
  1424. list_sentences_temp = []
  1425. list_entitys_temp = []
  1426. doc_id = article.id
  1427. _send_doc_id = article.doc_id
  1428. _title = article.title
  1429. #表格处理
  1430. key_preprocess = "tableToText"
  1431. start_time = time.time()
  1432. article_processed = article.content
  1433. if key_preprocess not in cost_time:
  1434. cost_time[key_preprocess] = 0
  1435. cost_time[key_preprocess] += time.time()-start_time
  1436. #nlp处理
  1437. if article_processed is not None and len(article_processed)!=0:
  1438. split_patten = "。"
  1439. sentences = []
  1440. _begin = 0
  1441. sentences_set = set()
  1442. for _iter in re.finditer(split_patten,article_processed):
  1443. _sen = article_processed[_begin:_iter.span()[1]]
  1444. if len(_sen)>0 and _sen not in sentences_set:
  1445. sentences.append(_sen)
  1446. sentences_set.add(_sen)
  1447. _begin = _iter.span()[1]
  1448. _sen = article_processed[_begin:]
  1449. if len(_sen)>0 and _sen not in sentences_set:
  1450. sentences.append(_sen)
  1451. sentences_set.add(_sen)
  1452. article.content = "".join(sentences)
  1453. # sentences.append(article_processed[_begin:])
  1454. lemmas = []
  1455. doc_offsets = []
  1456. dep_types = []
  1457. dep_tokens = []
  1458. time1 = time.time()
  1459. '''
  1460. tokens_all = fool.cut(sentences)
  1461. #pos_all = fool.LEXICAL_ANALYSER.pos(tokens_all)
  1462. #ner_tag_all = fool.LEXICAL_ANALYSER.ner_labels(sentences,tokens_all)
  1463. ner_entitys_all = fool.ner(sentences)
  1464. '''
  1465. #限流执行
  1466. key_nerToken = "nerToken"
  1467. start_time = time.time()
  1468. tokens_all = getTokens(sentences,useselffool=useselffool)
  1469. if key_nerToken not in cost_time:
  1470. cost_time[key_nerToken] = 0
  1471. cost_time[key_nerToken] += round(time.time()-start_time,2)
  1472. for sentence_index in range(len(sentences)):
  1473. sentence_text = sentences[sentence_index]
  1474. tokens = tokens_all[sentence_index]
  1475. #pos_tag = pos_all[sentence_index]
  1476. pos_tag = ""
  1477. ner_entitys = ""
  1478. list_sentences_temp.append(Sentences(doc_id=doc_id,sentence_index=sentence_index,sentence_text=sentence_text,tokens=tokens,pos_tags=pos_tag,ner_tags=ner_entitys))
  1479. if len(list_sentences_temp)==0:
  1480. list_sentences_temp.append(Sentences(doc_id=doc_id,sentence_index=0,sentence_text="sentence_text",tokens=[],pos_tags=[],ner_tags=""))
  1481. list_sentences.append(list_sentences_temp)
  1482. return list_sentences
  1483. def get_preprocessed_entitys(list_sentences,useselffool=True,cost_time=dict()):
  1484. '''
  1485. :param list_sentences:分局情况
  1486. :param cost_time:
  1487. :return: list_entitys
  1488. '''
  1489. list_entitys = []
  1490. for list_sentence in list_sentences:
  1491. sentences = []
  1492. list_entitys_temp = []
  1493. for _sentence in list_sentence:
  1494. sentences.append(_sentence.sentence_text)
  1495. lemmas = []
  1496. doc_offsets = []
  1497. dep_types = []
  1498. dep_tokens = []
  1499. time1 = time.time()
  1500. '''
  1501. tokens_all = fool.cut(sentences)
  1502. #pos_all = fool.LEXICAL_ANALYSER.pos(tokens_all)
  1503. #ner_tag_all = fool.LEXICAL_ANALYSER.ner_labels(sentences,tokens_all)
  1504. ner_entitys_all = fool.ner(sentences)
  1505. '''
  1506. #限流执行
  1507. key_nerToken = "nerToken"
  1508. start_time = time.time()
  1509. found_yeji = 0 # 2021/8/6 增加判断是否正文包含评标结果 及类似业绩判断用于过滤后面的金额
  1510. # found_pingbiao = False
  1511. ner_entitys_all = getNers(sentences,useselffool=useselffool)
  1512. if key_nerToken not in cost_time:
  1513. cost_time[key_nerToken] = 0
  1514. cost_time[key_nerToken] += round(time.time()-start_time,2)
  1515. for sentence_index in range(len(list_sentence)):
  1516. list_sentence_entitys = []
  1517. sentence_text = list_sentence[sentence_index].sentence_text
  1518. tokens = list_sentence[sentence_index].tokens
  1519. doc_id = list_sentence[sentence_index].doc_id
  1520. list_tokenbegin = []
  1521. begin = 0
  1522. for i in range(0,len(tokens)):
  1523. list_tokenbegin.append(begin)
  1524. begin += len(str(tokens[i]))
  1525. list_tokenbegin.append(begin+1)
  1526. #pos_tag = pos_all[sentence_index]
  1527. pos_tag = ""
  1528. ner_entitys = ner_entitys_all[sentence_index]
  1529. '''正则识别角色实体 经营部|经销部|电脑部|服务部|复印部|印刷部|彩印部|装饰部|修理部|汽修部|修理店|零售店|设计店|服务店|家具店|专卖店|分店|文具行|商行|印刷厂|修理厂|维修中心|修配中心|养护中心|服务中心|会馆|文化馆|超市|门市|商场|家具城|印刷社|经销处'''
  1530. for it in re.finditer(
  1531. '(?P<text_key_word>[^,。、;《]{,5}(单一来源|中标|中选|中价|成交)?(供应商|供货商|服务商|候选人|单位|人)(名称)?[为::]+)(?P<text>([^,。、;《]{5,20})(厂|中心|超市|门市|商场|工作室|文印室|城|部|店|站|馆|行|社|处))[,。]',
  1532. sentence_text):
  1533. for k, v in it.groupdict().items():
  1534. if k == 'text_key_word':
  1535. keyword = v
  1536. if k == 'text':
  1537. entity = v
  1538. b = it.start() + len(keyword)
  1539. e = it.end() - 1
  1540. if (b, e, 'org', entity) not in ner_entitys and (b, e, 'company', entity) not in ner_entitys:
  1541. ner_entitys.append((b, e, 'company', entity))
  1542. for it in re.finditer(
  1543. '(?P<text_key_word>((建设|招租|招标|采购)(单位|人)|业主)(名称)?[为::]+)(?P<text>\w{2,4}[省市县区镇]([^,。、;《]{2,20})(管理处|办公室|委员会|村委会|纪念馆|监狱|管教所|修养所|社区|农场|林场|羊场|猪场|石场|村|幼儿园))[,。]',
  1544. sentence_text):
  1545. for k, v in it.groupdict().items():
  1546. if k == 'text_key_word':
  1547. keyword = v
  1548. if k == 'text':
  1549. entity = v
  1550. b = it.start() + len(keyword)
  1551. e = it.end() - 1
  1552. if (b, e, 'org', entity) not in ner_entitys and (b, e, 'company', entity) not in ner_entitys:
  1553. ner_entitys.append((b, e, 'org', entity))
  1554. #识别package
  1555. #识别实体
  1556. for ner_entity in ner_entitys:
  1557. begin_index_temp = ner_entity[0]
  1558. end_index_temp = ner_entity[1]
  1559. entity_type = ner_entity[2]
  1560. entity_text = ner_entity[3]
  1561. if entity_type in ["org","company"] and not isLegalEnterprise(entity_text):
  1562. continue
  1563. for j in range(len(list_tokenbegin)):
  1564. if list_tokenbegin[j]==begin_index_temp:
  1565. begin_index = j
  1566. break
  1567. elif list_tokenbegin[j]>begin_index_temp:
  1568. begin_index = j-1
  1569. break
  1570. begin_index_temp += len(str(entity_text))
  1571. for j in range(begin_index,len(list_tokenbegin)):
  1572. if list_tokenbegin[j]>=begin_index_temp:
  1573. end_index = j-1
  1574. break
  1575. entity_id = "%s_%d_%d_%d"%(doc_id,sentence_index,begin_index,end_index)
  1576. #去掉标点符号
  1577. entity_text = re.sub("[,,。:!&@$\*]","",entity_text)
  1578. entity_text = entity_text.replace("(","(").replace(")",")") if isinstance(entity_text,str) else entity_text
  1579. list_sentence_entitys.append(Entity(doc_id,entity_id,entity_text,entity_type,sentence_index,begin_index,end_index,ner_entity[0],ner_entity[1]-1))
  1580. # 标记文章末尾的"发布人”、“发布时间”实体
  1581. if sentence_index==len(list_sentence)-1:
  1582. if len(list_sentence_entitys[-2:])>2:
  1583. second2last = list_sentence_entitys[-2]
  1584. last = list_sentence_entitys[-1]
  1585. if (second2last.entity_type in ["company",'org'] and last.entity_type=="time") or (
  1586. second2last.entity_type=="time" and last.entity_type in ["company",'org']):
  1587. if last.wordOffset_begin - second2last.wordOffset_end < 6 and len(sentence_text) - last.wordOffset_end<6:
  1588. last.is_tail = True
  1589. second2last.is_tail = True
  1590. #使用正则识别金额
  1591. entity_type = "money"
  1592. #money_patten_str = "(([1-9][\d,,]*(?:\.\d+)?[百千万亿]?[\(\)()元整]+)|([零壹贰叁肆伍陆柒捌玖拾佰仟萬億十百千万亿元角分]{3,})|(?:[¥¥]+,?|报价|标价)[(\(]?([万])?元?[)\)]?[::]?.{,7}?([1-9][\d,,]*(?:\.\d+)?(?:,?)[百千万亿]?)|([1-9][\d,,]*(?:\.\d+)?(?:,?)[百千万亿]?)[\((]?([万元]{1,2}))*"
  1593. # list_money_pattern = {"cn":"(()()(?P<money_cn>[零壹贰叁肆伍陆柒捌玖拾佰仟萬億圆十百千万亿元角分]{3,})())",
  1594. # "key_word":"((?P<text_key_word>(?:[¥¥]+,?|[单报标限]价|金额|价格|标的基本情况|CNY|成交结果:)(?:[,(\(]*\s*(?P<unit_key_word_before>[万元]*(?P<filter_unit2>[台个只]*))\s*[)\)]?)\s*[,,::]*(\s*[^壹贰叁肆伍陆柒捌玖拾佰仟萬億分万元]{,8}?))(?P<money_key_word>[0-9][\d,]*(?:\.\d+)?(?:,?)[百千万亿元]*)(?:[(\(]?(?P<filter_>[%])*\s*(?P<unit_key_word_behind>[万元]*(?P<filter_unit1>[台个只]*))\s*[)\)]?))",
  1595. # "front_m":"((?P<text_front_m>(?:[(\(]?\s*(?P<unit_front_m_before>[万元]+)\s*[)\)])\s*[,,::]*(\s*[^壹贰叁肆伍陆柒捌玖拾佰仟萬億分万元]{,7}?))(?P<money_front_m>[0-9][\d,]*(?:\.\d+)?(?:,?)[百千万亿元]*)())",
  1596. # "behind_m":"(()()(?P<money_behind_m>[0-9][\d,,]*(?:\.\d+)?(?:,?)[百千万亿]*)[\((]?(?P<unit_behind_m>[万元]+(?P<filter_unit3>[台个只]*))[\))]?)"}
  1597. list_money_pattern = {"cn":"(()()(?P<money_cn>[零壹贰叁肆伍陆柒捌玖拾佰仟萬億圆十百千万亿元角分]{3,})())",
  1598. "key_word": "((?P<text_key_word>(?:[¥¥]+,?|[单报标限总]价|金额|成交报?价|价格|预算|(监理|设计|勘察)(服务)?费|标的基本情况|CNY|成交结果|成交额|中标额)(?:[,,(\(]*\s*(人民币)?(?P<unit_key_word_before>[万亿]?元?(?P<filter_unit2>[台个只吨]*))\s*(/?费率)?(人民币)?[)\)]?)\s*[,,::]*(\s*[^壹贰叁肆伍陆柒捌玖拾佰仟萬億分万元编号时间]{,8}?))(第[123一二三]名[::])?(\d+(\*\d+%)+=)?(?P<money_key_word>[0-9][\d,]*(?:\.\d+)?(?:,?)[百千]{,1})(?:[(\(]?(?P<filter_>[%])*\s*(单位[::])?(?P<unit_key_word_behind>[万亿]?元?(?P<filter_unit1>[台只吨斤棵株页亩方条天]*))\s*[)\)]?))",
  1599. "front_m":"((?P<text_front_m>(?:[(\(]?\s*(?P<unit_front_m_before>[万亿]?元)\s*[)\)])\s*[,,::]*(\s*[^壹贰叁肆伍陆柒捌玖拾佰仟萬億分万元]{,7}?))(?P<money_front_m>[0-9][\d,]*(?:\.\d+)?(?:,?)[百千]*)())",
  1600. "behind_m":"(()()(?P<money_behind_m>[0-9][\d,]*(?:\.\d+)?(?:,?)[百千]*)(人民币)?[\((]?(?P<unit_behind_m>[万亿]?元(?P<filter_unit3>[台个只吨斤棵株页亩方条米]*))[\))]?)"}
  1601. # 2021/7/19 调整金额,单位提取正则,修复部分金额因为单位提取失败被过滤问题。
  1602. pattern_money = re.compile("%s|%s|%s|%s"%(list_money_pattern["cn"],list_money_pattern["key_word"],list_money_pattern["behind_m"],list_money_pattern["front_m"]))
  1603. set_begin = set()
  1604. # for pattern_key in list_money_pattern.keys():
  1605. # for pattern_key in ["cn","key_word","behind_m","front_m"]:
  1606. # # pattern = re.compile(list_money_pattern[pattern_key])
  1607. # pattern = re.compile("(()()([零壹贰叁肆伍陆柒捌玖拾佰仟萬億十百千万亿元角分]{3,})())*|((?:[¥¥]+,?|[报标限]价|金额)(?:[(\(]?\s*([万元]*)\s*[)\)]?)\s*[::]?(\s*[^壹贰叁肆伍陆柒捌玖拾佰仟萬億分]{,7}?)([0-9][\d,,]*(?:\.\d+)?(?:,?)[百千万亿元]*)(?:[(\(]?\s*([万元]*)\s*[)\)]?))*|(()()([0-9][\d,,]*(?:\.\d+)?(?:,?)[百千万亿]*)[\((]?([万元]+)[\))]?)*|((?:[(\(]?\s*([万元]+)\s*[)\)])\s*[::]?(\s*[^壹贰叁肆伍陆柒捌玖拾佰仟萬億分]{,7}?)([0-9][\d,,]*(?:\.\d+)?(?:,?)[百千万亿元]*)())*")
  1608. # all_match = re.findall(pattern, sentence_text)
  1609. # index = 0
  1610. # for i in range(len(all_match)):
  1611. # if len(all_match[i][0])>0:
  1612. # print("===",all_match[i])
  1613. # #print(all_match[i][0])
  1614. # unit = ""
  1615. # entity_text = all_match[i][3]
  1616. # if pattern_key in ["key_word","front_m"]:
  1617. # unit = all_match[i][1]
  1618. # if pattern_key=="key_word":
  1619. # if all_match[i][1]=="" and all_match[i][4]!="":
  1620. # unit = all_match[i][4]
  1621. # else:
  1622. # unit = all_match[i][4]
  1623. # if entity_text.find("元")>=0:
  1624. # unit = ""
  1625. #
  1626. # index += len(all_match[i][0])-len(entity_text)-len(all_match[i][4])#-len(all_match[i][1])-len(all_match[i][2])#整个提出来的作为实体->数字部分作为整体,否则会丢失特征
  1627. # begin_index_temp = index
  1628. # for j in range(len(list_tokenbegin)):
  1629. # if list_tokenbegin[j]==index:
  1630. # begin_index = j
  1631. # break
  1632. # elif list_tokenbegin[j]>index:
  1633. # begin_index = j-1
  1634. # break
  1635. # index += len(str(entity_text))+len(all_match[i][4])#+len(all_match[i][2])+len(all_match[i][1])#整个提出来的作为实体
  1636. # end_index_temp = index
  1637. # #index += len(str(all_match[i][0]))
  1638. # for j in range(begin_index,len(list_tokenbegin)):
  1639. # if list_tokenbegin[j]>=index:
  1640. # end_index = j-1
  1641. # break
  1642. # entity_id = "%s_%d_%d_%d"%(doc_id,sentence_index,begin_index,end_index)
  1643. #
  1644. # entity_text = re.sub("[^0-9.零壹贰叁肆伍陆柒捌玖拾佰仟萬億十百千万亿元角分]","",entity_text)
  1645. # if len(unit)>0:
  1646. # entity_text = str(getUnifyMoney(entity_text)*getMultipleFactor(unit[0]))
  1647. # else:
  1648. # entity_text = str(getUnifyMoney(entity_text))
  1649. #
  1650. # _exists = False
  1651. # for item in list_sentence_entitys:
  1652. # if item.entity_id==entity_id and item.entity_type==entity_type:
  1653. # _exists = True
  1654. # if not _exists:
  1655. # if float(entity_text)>1:
  1656. # list_sentence_entitys.append(Entity(doc_id,entity_id,entity_text,entity_type,sentence_index,begin_index,end_index,begin_index_temp,end_index_temp))
  1657. #
  1658. # else:
  1659. # index += 1
  1660. # if re.search('评标结果|候选人公示', sentence_text):
  1661. # found_pingbiao = True
  1662. if re.search('业绩', sentence_text):
  1663. found_yeji += 1
  1664. if found_yeji >= 2: # 过滤掉业绩后面的所有金额
  1665. all_match = []
  1666. else:
  1667. all_match = re.finditer(pattern_money, sentence_text)
  1668. index = 0
  1669. for _match in all_match:
  1670. if len(_match.group())>0:
  1671. # print("===",_match.group())
  1672. # # print(_match.groupdict())
  1673. notes = '' # 2021/7/20 新增备注金额大写或金额单位 if 金额大写 notes=大写 elif 单位 notes=单位
  1674. unit = ""
  1675. entity_text = ""
  1676. text_beforeMoney = ""
  1677. filter = ""
  1678. filter_unit = False
  1679. notSure = False
  1680. if re.search('业绩', sentence_text[:_match.span()[0]]): # 2021/7/21过滤掉业绩后面金额
  1681. # print('金额在业绩后面: ', _match.group(0))
  1682. found_yeji += 1
  1683. break
  1684. for k,v in _match.groupdict().items():
  1685. if v!="" and v is not None:
  1686. if k=='text_key_word':
  1687. notSure = True
  1688. if k.split("_")[0]=="money":
  1689. entity_text = v
  1690. if k.split("_")[0]=="unit":
  1691. unit = v
  1692. if k.split("_")[0]=="text":
  1693. text_beforeMoney = v
  1694. if k.split("_")[0]=="filter":
  1695. filter = v
  1696. if re.search("filter_unit",k) is not None:
  1697. filter_unit = True
  1698. if re.search('(^\d{2,},\d{4,}万?$)|(^\d{2,},\d{2}万?$)', entity_text.strip()): # 2021/7/19 修正OCR识别小数点为逗号
  1699. if re.search('[幢栋号楼层]', sentence_text[max(0, _match.span()[0]-2):_match.span()[0]]):
  1700. entity_text = re.sub('\d+,', '', entity_text)
  1701. else:
  1702. entity_text = entity_text.replace(',', '.')
  1703. # print(' 修正OCR识别小数点为逗号')
  1704. if entity_text.find("元")>=0:
  1705. unit = ""
  1706. if unit == "": #2021/7/21 有明显金额特征的补充单位,避免被过滤
  1707. if ('¥' in text_beforeMoney or '¥' in text_beforeMoney):
  1708. unit = '元'
  1709. # print('明显金额特征补充单位 元')
  1710. elif re.search('[单报标限]价|金额|价格|(监理|设计|勘察)(服务)?费[::为]+$', text_beforeMoney.strip()) and \
  1711. re.search('\d{5,}',entity_text) and re.search('^0|1[3|4|5|6|7|8|9]\d{9}',entity_text)==None:
  1712. unit = '元'
  1713. # print('明显金额特征补充单位 元')
  1714. elif re.search('(^\d{,3}(,?\d{3})+(\.\d{2,7},?)$)|(^\d{,3}(,\d{3})+,?$)',entity_text):
  1715. unit = '元'
  1716. # print('明显金额特征补充单位 元')
  1717. if unit.find("万") >= 0 and entity_text.find("万") >= 0: #2021/7/19修改为金额文本有万,不计算单位
  1718. # print('修正金额及单位都有万, 金额:',entity_text, '单位:',unit)
  1719. unit = "元"
  1720. if re.search('.*万元万元', entity_text): #2021/7/19 修正两个万元
  1721. # print(' 修正两个万元',entity_text)
  1722. entity_text = entity_text.replace('万元万元','万元')
  1723. else:
  1724. if filter_unit:
  1725. continue
  1726. if filter!="":
  1727. continue
  1728. index = _match.span()[0]+len(text_beforeMoney)
  1729. begin_index_temp = index
  1730. for j in range(len(list_tokenbegin)):
  1731. if list_tokenbegin[j]==index:
  1732. begin_index = j
  1733. break
  1734. elif list_tokenbegin[j]>index:
  1735. begin_index = j-1
  1736. break
  1737. index = _match.span()[1]
  1738. end_index_temp = index
  1739. #index += len(str(all_match[i][0]))
  1740. for j in range(begin_index,len(list_tokenbegin)):
  1741. if list_tokenbegin[j]>=index:
  1742. end_index = j-1
  1743. break
  1744. entity_id = "%s_%d_%d_%d"%(doc_id,sentence_index,begin_index,end_index)
  1745. entity_text = re.sub("[^0-9.零壹贰叁肆伍陆柒捌玖拾佰仟萬億圆十百千万亿元角分]","",entity_text)
  1746. # print('转换前金额:', entity_text, '单位:', unit, '备注:',notes, 'text_beforeMoney:',text_beforeMoney)
  1747. if re.search('总投资|投资总额|总预算|总概算|投资规模', sentence_text[max(0, _match.span()[0] - 8):_match.span()[1]]): # 2021/8/5过滤掉总投资金额
  1748. # print('总投资金额: ', _match.group(0))
  1749. notes = '总投资'
  1750. elif re.search('投资', sentence_text[max(0, _match.span()[0] - 8):_match.span()[1]]): # 2021/11/18 投资金额不作为招标金额
  1751. notes = '投资'
  1752. elif re.search('工程造价', sentence_text[max(0, _match.span()[0] - 8):_match.span()[1]]): # 2021/12/20 工程造价不作为招标金额
  1753. notes = '工程造价'
  1754. elif (re.search('保证金', sentence_text[max(0, _match.span()[0] - 5):_match.span()[1]])
  1755. or re.search('保证金的?(缴纳)?(金额|金\?|额|\?)?[\((]*(万?元|为?人民币|大写|调整|变更|已?修改|更改|更正)?[\))]*[::为]',
  1756. sentence_text[max(0, _match.span()[0] - 10):_match.span()[1]])
  1757. or re.search('保证金由[\d.,]+.{,3}(变更|修改|更改|更正|调整?)为',
  1758. sentence_text[max(0, _match.span()[0] - 15):_match.span()[1]])):
  1759. notes = '保证金'
  1760. # print('保证金信息:', sentence_text[max(0, _match.span()[0] - 15):_match.span()[1]])
  1761. elif re.search('成本(警戒|预警)(线|价|值)[^0-9元]{,10}',
  1762. sentence_text[max(0, _match.span()[0] - 10):_match.span()[0]]):
  1763. notes = '成本警戒线'
  1764. elif re.search('(监理|设计|勘察)(服务)?费(报价)?[约为:]', sentence_text[_match.span()[0]:_match.span()[1]]):
  1765. cost_re = re.search('(监理|设计|勘察)(服务)?费', sentence_text[_match.span()[0]:_match.span()[1]])
  1766. notes = cost_re.group(1)
  1767. elif re.search('单价|总金额', sentence_text[_match.span()[0]:_match.span()[1]]):
  1768. notes = '单价'
  1769. elif re.search('[零壹贰叁肆伍陆柒捌玖拾佰仟萬億圆]', entity_text) != None:
  1770. notes = '大写'
  1771. if entity_text[0] == "拾": # 2021/12/16 修正大写金额省略了数字转换错误问题
  1772. entity_text = "壹"+entity_text
  1773. # print("补充备注:notes = 大写")
  1774. if len(unit)>0:
  1775. if unit.find('万')>=0 and len(entity_text.split('.')[0])>=8: # 2021/7/19 修正万元金额过大的情况
  1776. # print('修正单位万元金额过大的情况 金额:', entity_text, '单位:', unit)
  1777. entity_text = str(getUnifyMoney(entity_text) * getMultipleFactor(unit[0])/10000)
  1778. unit = '元' # 修正金额后单位 重置为元
  1779. else:
  1780. # print('str(getUnifyMoney(entity_text)*getMultipleFactor(unit[0])):')
  1781. entity_text = str(getUnifyMoney(entity_text)*getMultipleFactor(unit[0]))
  1782. else:
  1783. if entity_text.find('万')>=0 and entity_text.split('.')[0].isdigit() and len(entity_text.split('.')[0])>=8:
  1784. entity_text = str(getUnifyMoney(entity_text)/10000)
  1785. # print('修正金额字段含万 过大的情况')
  1786. else:
  1787. entity_text = str(getUnifyMoney(entity_text))
  1788. if float(entity_text)<100 or float(entity_text)>100000000000:
  1789. # print('过滤掉金额:float(entity_text)<100 or float(entity_text)>100000000000', entity_text, unit)
  1790. continue
  1791. if notSure and unit=="" and float(entity_text)>100*10000:
  1792. # print('过滤掉金额 notSure and unit=="" and float(entity_text)>100*10000:', entity_text, unit)
  1793. continue
  1794. _exists = False
  1795. for item in list_sentence_entitys:
  1796. if item.entity_id==entity_id and item.entity_type==entity_type:
  1797. _exists = True
  1798. if (begin_index >=item.begin_index and begin_index<=item.end_index) or (end_index>=item.begin_index and end_index<=item.end_index):
  1799. _exists = True
  1800. if not _exists:
  1801. if float(entity_text)>1:
  1802. list_sentence_entitys.append(Entity(doc_id,entity_id,entity_text,entity_type,sentence_index,begin_index,end_index,begin_index_temp,end_index_temp))
  1803. list_sentence_entitys[-1].notes = notes # 2021/7/20 新增金额备注
  1804. list_sentence_entitys[-1].money_unit = unit # 2021/7/20 新增金额备注
  1805. # print('预处理中的 金额:%s, 单位:%s'%(entity_text,unit))
  1806. else:
  1807. index += 1
  1808. # "联系人"正则补充提取 2021/11/15 新增
  1809. list_person_text = [entity.entity_text for entity in list_sentence_entitys if entity.entity_type=='person']
  1810. error_text = ['交易','机构','教育','项目','公司','中标','开标','截标','监督','政府','国家','中国','技术','投标','传真','网址','电子邮',
  1811. '联系','联系电','联系地','采购代','邮政编','邮政','电话','手机','手机号','联系人','地址','地点','邮箱','邮编','联系方','招标','招标人','代理','代理人','采购','附件']
  1812. list_person_text = set(list_person_text + error_text)
  1813. re_person = re.compile("联系人[::]([\u4e00-\u9fa5]工)|"
  1814. "联系人[::]([\u4e00-\u9fa5]{2,3})(?=联系)|"
  1815. "联系人[::]([\u4e00-\u9fa5]{2,3})")
  1816. list_person = []
  1817. for match_result in re_person.finditer(sentence_text):
  1818. match_text = match_result.group()
  1819. entity_text = match_text[4:]
  1820. wordOffset_begin = match_result.start() + 4
  1821. wordOffset_end = match_result.end()
  1822. # print(text[wordOffset_begin:wordOffset_end])
  1823. # 排除一些不为人名的实体
  1824. if re.search("^[\u4e00-\u9fa5]{7,}([,。]|$)",sentence_text[wordOffset_begin:wordOffset_begin+20]):
  1825. continue
  1826. if entity_text not in list_person_text and entity_text[:2] not in list_person_text:
  1827. _person = dict()
  1828. _person['body'] = entity_text
  1829. _person['begin_index'] = wordOffset_begin
  1830. _person['end_index'] = wordOffset_end
  1831. list_person.append(_person)
  1832. entity_type = "person"
  1833. for person in list_person:
  1834. begin_index_temp = person['begin_index']
  1835. for j in range(len(list_tokenbegin)):
  1836. if list_tokenbegin[j] == begin_index_temp:
  1837. begin_index = j
  1838. break
  1839. elif list_tokenbegin[j] > begin_index_temp:
  1840. begin_index = j - 1
  1841. break
  1842. index = person['end_index']
  1843. end_index_temp = index
  1844. for j in range(begin_index, len(list_tokenbegin)):
  1845. if list_tokenbegin[j] >= index:
  1846. end_index = j - 1
  1847. break
  1848. entity_id = "%s_%d_%d_%d" % (doc_id, sentence_index, begin_index, end_index)
  1849. entity_text = person['body']
  1850. list_sentence_entitys.append(
  1851. Entity(doc_id, entity_id, entity_text, entity_type, sentence_index, begin_index, end_index,
  1852. begin_index_temp, end_index_temp))
  1853. # 资金来源提取 2020/12/30 新增
  1854. list_moneySource = extract_moneySource(sentence_text)
  1855. entity_type = "moneysource"
  1856. for moneySource in list_moneySource:
  1857. begin_index_temp = moneySource['begin_index']
  1858. for j in range(len(list_tokenbegin)):
  1859. if list_tokenbegin[j] == begin_index_temp:
  1860. begin_index = j
  1861. break
  1862. elif list_tokenbegin[j] > begin_index_temp:
  1863. begin_index = j - 1
  1864. break
  1865. index = moneySource['end_index']
  1866. end_index_temp = index
  1867. for j in range(begin_index, len(list_tokenbegin)):
  1868. if list_tokenbegin[j] >= index:
  1869. end_index = j - 1
  1870. break
  1871. entity_id = "%s_%d_%d_%d" % (doc_id, sentence_index, begin_index, end_index)
  1872. entity_text = moneySource['body']
  1873. list_sentence_entitys.append(
  1874. Entity(doc_id, entity_id, entity_text, entity_type, sentence_index, begin_index, end_index,
  1875. begin_index_temp, end_index_temp))
  1876. # 电子邮箱提取 2021/11/04 新增
  1877. list_email = extract_email(sentence_text)
  1878. entity_type = "email" # 电子邮箱
  1879. for email in list_email:
  1880. begin_index_temp = email['begin_index']
  1881. for j in range(len(list_tokenbegin)):
  1882. if list_tokenbegin[j] == begin_index_temp:
  1883. begin_index = j
  1884. break
  1885. elif list_tokenbegin[j] > begin_index_temp:
  1886. begin_index = j - 1
  1887. break
  1888. index = email['end_index']
  1889. end_index_temp = index
  1890. for j in range(begin_index, len(list_tokenbegin)):
  1891. if list_tokenbegin[j] >= index:
  1892. end_index = j - 1
  1893. break
  1894. entity_id = "%s_%d_%d_%d" % (doc_id, sentence_index, begin_index, end_index)
  1895. entity_text = email['body']
  1896. list_sentence_entitys.append(
  1897. Entity(doc_id, entity_id, entity_text, entity_type, sentence_index, begin_index, end_index,
  1898. begin_index_temp, end_index_temp))
  1899. # 服务期限提取 2020/12/30 新增
  1900. list_servicetime = extract_servicetime(sentence_text)
  1901. entity_type = "serviceTime"
  1902. for servicetime in list_servicetime:
  1903. begin_index_temp = servicetime['begin_index']
  1904. for j in range(len(list_tokenbegin)):
  1905. if list_tokenbegin[j] == begin_index_temp:
  1906. begin_index = j
  1907. break
  1908. elif list_tokenbegin[j] > begin_index_temp:
  1909. begin_index = j - 1
  1910. break
  1911. index = servicetime['end_index']
  1912. end_index_temp = index
  1913. for j in range(begin_index, len(list_tokenbegin)):
  1914. if list_tokenbegin[j] >= index:
  1915. end_index = j - 1
  1916. break
  1917. entity_id = "%s_%d_%d_%d" % (doc_id, sentence_index, begin_index, end_index)
  1918. entity_text = servicetime['body']
  1919. list_sentence_entitys.append(
  1920. Entity(doc_id, entity_id, entity_text, entity_type, sentence_index, begin_index, end_index,
  1921. begin_index_temp, end_index_temp))
  1922. # 招标方式提取 2020/12/30 新增
  1923. # list_bidway = extract_bidway(sentence_text, )
  1924. # entity_type = "bidway"
  1925. # for bidway in list_bidway:
  1926. # begin_index_temp = bidway['begin_index']
  1927. # end_index_temp = bidway['end_index']
  1928. # begin_index = changeIndexFromWordToWords(tokens, begin_index_temp)
  1929. # end_index = changeIndexFromWordToWords(tokens, end_index_temp)
  1930. # if begin_index is None or end_index is None:
  1931. # continue
  1932. # print(begin_index_temp,end_index_temp,begin_index,end_index)
  1933. # entity_id = "%s_%d_%d_%d" % (doc_id, sentence_index, begin_index, end_index)
  1934. # entity_text = bidway['body']
  1935. # list_sentence_entitys.append(
  1936. # Entity(doc_id, entity_id, entity_text, entity_type, sentence_index, begin_index, end_index,
  1937. # begin_index_temp, end_index_temp))
  1938. list_sentence_entitys.sort(key=lambda x:x.begin_index)
  1939. list_entitys_temp = list_entitys_temp+list_sentence_entitys
  1940. list_entitys.append(list_entitys_temp)
  1941. return list_entitys
  1942. def union_result(codeName,prem):
  1943. '''
  1944. @summary:模型的结果拼成字典
  1945. @param:
  1946. codeName:编号名称模型的结果字典
  1947. prem:拿到属性的角色的字典
  1948. @return:拼接起来的字典
  1949. '''
  1950. result = []
  1951. assert len(codeName)==len(prem)
  1952. for item_code,item_prem in zip(codeName,prem):
  1953. result.append(dict(item_code,**item_prem))
  1954. return result
  1955. def persistenceData(data):
  1956. '''
  1957. @summary:将中间结果保存到数据库-线上生产的时候不需要执行
  1958. '''
  1959. import psycopg2
  1960. conn = psycopg2.connect(dbname="BiddingKG",user="postgres",password="postgres",host="192.168.2.101")
  1961. cursor = conn.cursor()
  1962. for item_index in range(len(data)):
  1963. item = data[item_index]
  1964. doc_id = item[0]
  1965. dic = item[1]
  1966. code = dic['code']
  1967. name = dic['name']
  1968. prem = dic['prem']
  1969. if len(code)==0:
  1970. code_insert = ""
  1971. else:
  1972. code_insert = ";".join(code)
  1973. prem_insert = ""
  1974. for item in prem:
  1975. for x in item:
  1976. if isinstance(x, list):
  1977. if len(x)>0:
  1978. for x1 in x:
  1979. prem_insert+="/".join(x1)+","
  1980. prem_insert+="$"
  1981. else:
  1982. prem_insert+=str(x)+"$"
  1983. prem_insert+=";"
  1984. sql = " insert into predict_validation(doc_id,code,name,prem) values('"+doc_id+"','"+code_insert+"','"+name+"','"+prem_insert+"')"
  1985. cursor.execute(sql)
  1986. conn.commit()
  1987. conn.close()
  1988. def persistenceData1(list_entitys,list_sentences):
  1989. '''
  1990. @summary:将中间结果保存到数据库-线上生产的时候不需要执行
  1991. '''
  1992. import psycopg2
  1993. conn = psycopg2.connect(dbname="BiddingKG",user="postgres",password="postgres",host="192.168.2.101")
  1994. cursor = conn.cursor()
  1995. for list_entity in list_entitys:
  1996. for entity in list_entity:
  1997. if entity.values is not None:
  1998. sql = " insert into predict_entity(entity_id,entity_text,entity_type,doc_id,sentence_index,begin_index,end_index,label,values) values('"+str(entity.entity_id)+"','"+str(entity.entity_text)+"','"+str(entity.entity_type)+"','"+str(entity.doc_id)+"',"+str(entity.sentence_index)+","+str(entity.begin_index)+","+str(entity.end_index)+","+str(entity.label)+",array"+str(entity.values)+")"
  1999. else:
  2000. sql = " insert into predict_entity(entity_id,entity_text,entity_type,doc_id,sentence_index,begin_index,end_index) values('"+str(entity.entity_id)+"','"+str(entity.entity_text)+"','"+str(entity.entity_type)+"','"+str(entity.doc_id)+"',"+str(entity.sentence_index)+","+str(entity.begin_index)+","+str(entity.end_index)+")"
  2001. cursor.execute(sql)
  2002. for list_sentence in list_sentences:
  2003. for sentence in list_sentence:
  2004. str_tokens = "["
  2005. for item in sentence.tokens:
  2006. str_tokens += "'"
  2007. if item=="'":
  2008. str_tokens += "''"
  2009. else:
  2010. str_tokens += item
  2011. str_tokens += "',"
  2012. str_tokens = str_tokens[:-1]+"]"
  2013. sql = " insert into predict_sentences(doc_id,sentence_index,tokens) values('"+sentence.doc_id+"',"+str(sentence.sentence_index)+",array"+str_tokens+")"
  2014. cursor.execute(sql)
  2015. conn.commit()
  2016. conn.close()
  2017. def _handle(item,result_queue):
  2018. dochtml = item["dochtml"]
  2019. docid = item["docid"]
  2020. list_innerTable = tableToText(BeautifulSoup(dochtml,"lxml"))
  2021. flag = False
  2022. if list_innerTable:
  2023. flag = True
  2024. for table in list_innerTable:
  2025. result_queue.put({"docid":docid,"json_table":json.dumps(table,ensure_ascii=False)})
  2026. def getPredictTable():
  2027. filename = "D:\Workspace2016\DataExport\data\websouce_doc.csv"
  2028. import pandas as pd
  2029. import json
  2030. from BiddingKG.dl.common.MultiHandler import MultiHandler,Queue
  2031. df = pd.read_csv(filename)
  2032. df_data = {"json_table":[],"docid":[]}
  2033. _count = 0
  2034. _sum = len(df["docid"])
  2035. task_queue = Queue()
  2036. result_queue = Queue()
  2037. _index = 0
  2038. for dochtml,docid in zip(df["dochtmlcon"],df["docid"]):
  2039. task_queue.put({"docid":docid,"dochtml":dochtml,"json_table":None})
  2040. _index += 1
  2041. mh = MultiHandler(task_queue=task_queue,task_handler=_handle,result_queue=result_queue,process_count=5,thread_count=1)
  2042. mh.run()
  2043. while True:
  2044. try:
  2045. item = result_queue.get(block=True,timeout=1)
  2046. df_data["docid"].append(item["docid"])
  2047. df_data["json_table"].append(item["json_table"])
  2048. except Exception as e:
  2049. print(e)
  2050. break
  2051. df_1 = pd.DataFrame(df_data)
  2052. df_1.to_csv("../form/websource_67000_table.csv",columns=["docid","json_table"])
  2053. if __name__=="__main__":
  2054. '''
  2055. import glob
  2056. for file in glob.glob("C:\\Users\\User\\Desktop\\test\\*.html"):
  2057. file_txt = str(file).replace("html","txt")
  2058. with codecs.open(file_txt,"a+",encoding="utf8") as f:
  2059. f.write("\n================\n")
  2060. content = codecs.open(file,"r",encoding="utf8").read()
  2061. f.write(segment(tableToText(BeautifulSoup(content,"lxml"))))
  2062. '''
  2063. # content = codecs.open("C:\\Users\\User\\Desktop\\2.html","r",encoding="utf8").read()
  2064. # print(segment(tableToText(BeautifulSoup(content,"lxml"))))
  2065. # getPredictTable()
  2066. with open('D:/138786703.html', 'r', encoding='utf-8') as f:
  2067. sourceContent = f.read()
  2068. # article_processed = segment(tableToText(BeautifulSoup(sourceContent, "lxml")))
  2069. # print(article_processed)
  2070. list_articles, list_sentences, list_entitys, _cost_time = get_preprocessed([['doc_id', sourceContent, "", "", '', '2021-02-01']], useselffool=True)
  2071. for entity in list_entitys[0]:
  2072. print(entity.entity_type, entity.entity_text)