Preprocessing.py 153 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074
  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. from BiddingKG.dl.ratio.re_ratio import extract_ratio
  9. from BiddingKG.dl.table_head.predict import predict
  10. sys.setrecursionlimit(1000000)
  11. sys.path.append(os.path.abspath("../.."))
  12. sys.path.append(os.path.abspath(".."))
  13. from BiddingKG.dl.common.Utils import *
  14. from BiddingKG.dl.interface.Entitys import *
  15. from BiddingKG.dl.interface.predictor import getPredictor
  16. from BiddingKG.dl.common.nerUtils import *
  17. from BiddingKG.dl.money.moneySource.ruleExtra import extract_moneySource
  18. from BiddingKG.dl.time.re_servicetime import extract_servicetime
  19. from BiddingKG.dl.relation_extraction.re_email import extract_email
  20. from BiddingKG.dl.bidway.re_bidway import extract_bidway,bidway_integrate
  21. from BiddingKG.dl.fingerprint.documentFingerprint import getFingerprint
  22. from BiddingKG.dl.entityLink.entityLink import *
  23. #
  24. def tableToText(soup):
  25. '''
  26. @param:
  27. soup:网页html的soup
  28. @return:处理完表格信息的网页text
  29. '''
  30. def getTrs(tbody):
  31. #获取所有的tr
  32. trs = []
  33. objs = tbody.find_all(recursive=False)
  34. for obj in objs:
  35. if obj.name=="tr":
  36. trs.append(obj)
  37. if obj.name=="tbody":
  38. for tr in obj.find_all("tr",recursive=False):
  39. trs.append(tr)
  40. return trs
  41. def fixSpan(tbody):
  42. # 处理colspan, rowspan信息补全问题
  43. #trs = tbody.findChildren('tr', recursive=False)
  44. trs = getTrs(tbody)
  45. ths_len = 0
  46. ths = list()
  47. trs_set = set()
  48. #修改为先进行列补全再进行行补全,否则可能会出现表格解析混乱
  49. # 遍历每一个tr
  50. for indtr, tr in enumerate(trs):
  51. ths_tmp = tr.findChildren('th', recursive=False)
  52. #不补全含有表格的tr
  53. if len(tr.findChildren('table'))>0:
  54. continue
  55. if len(ths_tmp) > 0:
  56. ths_len = ths_len + len(ths_tmp)
  57. for th in ths_tmp:
  58. ths.append(th)
  59. trs_set.add(tr)
  60. # 遍历每行中的element
  61. tds = tr.findChildren(recursive=False)
  62. for indtd, td in enumerate(tds):
  63. # 若有colspan 则补全同一行下一个位置
  64. if 'colspan' in td.attrs:
  65. if str(re.sub("[^0-9]","",str(td['colspan'])))!="":
  66. col = int(re.sub("[^0-9]","",str(td['colspan'])))
  67. if col<100 and len(td.get_text())<1000:
  68. td['colspan'] = 1
  69. for i in range(1, col, 1):
  70. td.insert_after(copy.copy(td))
  71. for indtr, tr in enumerate(trs):
  72. ths_tmp = tr.findChildren('th', recursive=False)
  73. #不补全含有表格的tr
  74. if len(tr.findChildren('table'))>0:
  75. continue
  76. if len(ths_tmp) > 0:
  77. ths_len = ths_len + len(ths_tmp)
  78. for th in ths_tmp:
  79. ths.append(th)
  80. trs_set.add(tr)
  81. # 遍历每行中的element
  82. tds = tr.findChildren(recursive=False)
  83. for indtd, td in enumerate(tds):
  84. # 若有rowspan 则补全下一行同样位置
  85. if 'rowspan' in td.attrs:
  86. if str(re.sub("[^0-9]","",str(td['rowspan'])))!="":
  87. row = int(re.sub("[^0-9]","",str(td['rowspan'])))
  88. td['rowspan'] = 1
  89. for i in range(1, row, 1):
  90. # 获取下一行的所有td, 在对应的位置插入
  91. if indtr+i<len(trs):
  92. tds1 = trs[indtr + i].findChildren(['td','th'], recursive=False)
  93. if len(tds1) >= (indtd) and len(tds1)>0:
  94. if indtd > 0:
  95. tds1[indtd - 1].insert_after(copy.copy(td))
  96. else:
  97. tds1[0].insert_before(copy.copy(td))
  98. elif indtd-2>0 and len(tds1) > 0 and len(tds1) == indtd - 1: # 修正某些表格最后一列没补全
  99. tds1[indtd-2].insert_after(copy.copy(td))
  100. def getTable(tbody):
  101. #trs = tbody.findChildren('tr', recursive=False)
  102. trs = getTrs(tbody)
  103. inner_table = []
  104. for tr in trs:
  105. tr_line = []
  106. tds = tr.findChildren(['td','th'], recursive=False)
  107. if len(tds)==0:
  108. tr_line.append([re.sub('\xa0','',segment(tr,final=False)),0]) # 2021/12/21 修复部分表格没有td 造成数据丢失
  109. for td in tds:
  110. tr_line.append([re.sub('\xa0','',segment(td,final=False)),0])
  111. #tr_line.append([td.get_text(),0])
  112. inner_table.append(tr_line)
  113. return inner_table
  114. #处理表格不对齐的问题
  115. def fixTable(inner_table,fix_value="~~"):
  116. maxWidth = 0
  117. for item in inner_table:
  118. if len(item)>maxWidth:
  119. maxWidth = len(item)
  120. for i in range(len(inner_table)):
  121. if len(inner_table[i])<maxWidth:
  122. for j in range(maxWidth-len(inner_table[i])):
  123. inner_table[i].append([fix_value,0])
  124. return inner_table
  125. def removePadding(inner_table,pad_row = "@@",pad_col = "##"):
  126. height = len(inner_table)
  127. width = len(inner_table[0])
  128. for i in range(height):
  129. point = ""
  130. for j in range(width):
  131. if inner_table[i][j][0]==point and point!="":
  132. inner_table[i][j][0] = pad_row
  133. else:
  134. if inner_table[i][j][0] not in [pad_row,pad_col]:
  135. point = inner_table[i][j][0]
  136. for j in range(width):
  137. point = ""
  138. for i in range(height):
  139. if inner_table[i][j][0]==point and point!="":
  140. inner_table[i][j][0] = pad_col
  141. else:
  142. if inner_table[i][j][0] not in [pad_row,pad_col]:
  143. point = inner_table[i][j][0]
  144. def addPadding(inner_table,pad_row = "@@",pad_col = "##"):
  145. height = len(inner_table)
  146. width = len(inner_table[0])
  147. for i in range(height):
  148. for j in range(width):
  149. if inner_table[i][j][0]==pad_row:
  150. inner_table[i][j][0] = inner_table[i][j-1][0]
  151. inner_table[i][j][1] = inner_table[i][j-1][1]
  152. if inner_table[i][j][0]==pad_col:
  153. inner_table[i][j][0] = inner_table[i-1][j][0]
  154. inner_table[i][j][1] = inner_table[i-1][j][1]
  155. def repairTable(inner_table, dye_set=set(), key_set=set(), fix_value="~~"):
  156. """
  157. @summary: 修复表头识别,将明显错误的进行修正
  158. """
  159. def repairNeeded(line):
  160. first_1 = -1
  161. last_1 = -1
  162. first_0 = -1
  163. last_0 = -1
  164. count_1 = 0
  165. count_0 = 0
  166. for i in range(len(line)):
  167. if line[i][0]==fix_value:
  168. continue
  169. if line[i][1]==1:
  170. if first_1==-1:
  171. first_1 = i
  172. last_1 = i
  173. count_1 += 1
  174. if line[i][1]==0:
  175. if first_0 == -1:
  176. first_0 = i
  177. last_0 = i
  178. count_0 += 1
  179. if first_1 ==-1 or last_0 == -1:
  180. return False
  181. # 异常情况:第一个不是表头;最后一个是表头;表头个数远大于属性值个数
  182. if first_1-0 > 0 or last_0-len(line)+1 < 0 or last_1 == len(line)-1 or count_1-count_0 >= 3:
  183. return True
  184. return False
  185. def getsimilarity(line, line1):
  186. same_count = 0
  187. for item, item1 in zip(line,line1):
  188. if item[1] == item1[1]:
  189. same_count += 1
  190. return same_count/len(line)
  191. def selfrepair(inner_table,index,dye_set,key_set):
  192. """
  193. @summary: 计算每个节点受到的挤压度来判断是否需要染色
  194. """
  195. #print("B",inner_table[index])
  196. min_presure = 3
  197. list_dye = []
  198. first = None
  199. count = 0
  200. temp_set = set()
  201. _index = 0
  202. for item in inner_table[index]:
  203. if first is None:
  204. first = item[1]
  205. if item[0] not in temp_set:
  206. count += 1
  207. temp_set.add(item[0])
  208. else:
  209. if first == item[1]:
  210. if item[0] not in temp_set:
  211. temp_set.add(item[0])
  212. count += 1
  213. else:
  214. list_dye.append([first,count,_index])
  215. first = item[1]
  216. temp_set.add(item[0])
  217. count = 1
  218. _index += 1
  219. list_dye.append([first,count,_index])
  220. if len(list_dye)>1:
  221. begin = 0
  222. end = 0
  223. for i in range(len(list_dye)):
  224. end = list_dye[i][2]
  225. dye_flag = False
  226. # 首尾要求压力减一
  227. if i==0:
  228. if list_dye[i+1][1]-list_dye[i][1]+1>=min_presure-1:
  229. dye_flag = True
  230. dye_type = list_dye[i+1][0]
  231. elif i==len(list_dye)-1:
  232. if list_dye[i-1][1]-list_dye[i][1]+1>=min_presure-1:
  233. dye_flag = True
  234. dye_type = list_dye[i-1][0]
  235. else:
  236. if list_dye[i][1]>1:
  237. if list_dye[i+1][1]-list_dye[i][1]+1>=min_presure:
  238. dye_flag = True
  239. dye_type = list_dye[i+1][0]
  240. if list_dye[i-1][1]-list_dye[i][1]+1>=min_presure:
  241. dye_flag = True
  242. dye_type = list_dye[i-1][0]
  243. else:
  244. if list_dye[i+1][1]+list_dye[i-1][1]-list_dye[i][1]+1>=min_presure:
  245. dye_flag = True
  246. dye_type = list_dye[i+1][0]
  247. if list_dye[i+1][1]+list_dye[i-1][1]-list_dye[i][1]+1>=min_presure:
  248. dye_flag = True
  249. dye_type = list_dye[i-1][0]
  250. if dye_flag:
  251. for h in range(begin,end):
  252. inner_table[index][h][1] = dye_type
  253. dye_set.add((inner_table[index][h][0],dye_type))
  254. key_set.add(inner_table[index][h][0])
  255. begin = end
  256. #print("E",inner_table[index])
  257. def otherrepair(inner_table,index,dye_set,key_set):
  258. list_provide_repair = []
  259. if index==0 and len(inner_table)>1:
  260. list_provide_repair.append(index+1)
  261. elif index==len(inner_table)-1:
  262. list_provide_repair.append(index-1)
  263. else:
  264. list_provide_repair.append(index+1)
  265. list_provide_repair.append(index-1)
  266. for provide_index in list_provide_repair:
  267. if not repairNeeded(inner_table[provide_index]):
  268. same_prob = getsimilarity(inner_table[index], inner_table[provide_index])
  269. if same_prob>=0.8:
  270. for i in range(len(inner_table[provide_index])):
  271. if inner_table[index][i][1]!=inner_table[provide_index][i][1]:
  272. dye_set.add((inner_table[index][i][0],inner_table[provide_index][i][1]))
  273. key_set.add(inner_table[index][i][0])
  274. inner_table[index][i][1] = inner_table[provide_index][i][1]
  275. elif same_prob<=0.2:
  276. for i in range(len(inner_table[provide_index])):
  277. if inner_table[index][i][1]==inner_table[provide_index][i][1]:
  278. dye_set.add((inner_table[index][i][0],inner_table[provide_index][i][1]))
  279. key_set.add(inner_table[index][i][0])
  280. inner_table[index][i][1] = 0 if inner_table[provide_index][i][1] ==1 else 1
  281. len_dye_set = len(dye_set)
  282. height = len(inner_table)
  283. for i in range(height):
  284. if repairNeeded(inner_table[i]):
  285. selfrepair(inner_table, i, dye_set, key_set)
  286. #otherrepair(inner_table,i,dye_set,key_set)
  287. for h in range(len(inner_table)):
  288. for w in range(len(inner_table[0])):
  289. if inner_table[h][w][0] in key_set:
  290. for item in dye_set:
  291. if inner_table[h][w][0] == item[0]:
  292. inner_table[h][w][1] = item[1]
  293. # 如果两个set长度不相同,则有同一个key被反复染色,将导致无限迭代
  294. if len(dye_set) != len(key_set):
  295. for i in range(height):
  296. if repairNeeded(inner_table[i]):
  297. selfrepair(inner_table,i,dye_set,key_set)
  298. #otherrepair(inner_table,i,dye_set,key_set)
  299. return
  300. if len(dye_set) == len_dye_set:
  301. '''
  302. for i in range(height):
  303. if repairNeeded(inner_table[i]):
  304. otherrepair(inner_table,i,dye_set,key_set)
  305. '''
  306. return
  307. repairTable(inner_table, dye_set, key_set)
  308. def sliceTable(inner_table,fix_value="~~"):
  309. #进行分块
  310. height = len(inner_table)
  311. width = len(inner_table[0])
  312. head_list = []
  313. head_list.append(0)
  314. last_head = None
  315. last_is_same_value = False
  316. for h in range(height):
  317. is_all_key = True#是否是全表头行
  318. is_all_value = True#是否是全属性值
  319. is_same_with_lastHead = True#和上一行的结构是否相同
  320. is_same_value=True#一行的item都一样
  321. #is_same_first_item = True#与上一行的第一项是否相同
  322. same_value = inner_table[h][0][0]
  323. for w in range(width):
  324. if last_head is not None:
  325. if inner_table[h-1][w][0] != fix_value and inner_table[h-1][w][0] != "" and inner_table[h-1][w][1] == 0:
  326. is_all_key = False
  327. if inner_table[h][w][0]==1:
  328. is_all_value = False
  329. if inner_table[h][w][1]!= inner_table[h-1][w][1]:
  330. is_same_with_lastHead = False
  331. if inner_table[h][w][0]!=fix_value and inner_table[h][w][0]!=same_value:
  332. is_same_value = False
  333. else:
  334. if re.search("\d+",same_value) is not None:
  335. is_same_value = False
  336. if h>0 and inner_table[h][0][0]!=inner_table[h-1][0][0]:
  337. is_same_first_item = False
  338. last_head = h
  339. if last_is_same_value:
  340. last_is_same_value = is_same_value
  341. continue
  342. if is_same_value:
  343. # 该块只有表头一行不合法
  344. if h - head_list[-1] > 1:
  345. head_list.append(h)
  346. last_is_same_value = is_same_value
  347. continue
  348. if not is_all_key:
  349. if not is_same_with_lastHead:
  350. # 该块只有表头一行不合法
  351. if h - head_list[-1] > 1:
  352. head_list.append(h)
  353. head_list.append(height)
  354. return head_list
  355. def setHead_initem(inner_table,pat_head,fix_value="~~",prob_min=0.5):
  356. set_item = set()
  357. height = len(inner_table)
  358. width = len(inner_table[0])
  359. empty_set = set()
  360. for i in range(height):
  361. for j in range(width):
  362. item = inner_table[i][j][0]
  363. if item.strip()=="":
  364. empty_set.add(item)
  365. else:
  366. set_item.add(item)
  367. list_item = list(set_item)
  368. if list_item:
  369. x = []
  370. for item in list_item:
  371. x.append(getPredictor("form").encode(item))
  372. predict_y = getPredictor("form").predict(np.array(x),type="item")
  373. _dict = dict()
  374. for item,values in zip(list_item,list(predict_y)):
  375. _dict[item] = values[1]
  376. # print("##",item,values)
  377. #print(_dict)
  378. for i in range(height):
  379. for j in range(width):
  380. item = inner_table[i][j][0]
  381. if item not in empty_set:
  382. 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)
  383. # print("=====")
  384. # for item in inner_table:
  385. # print(item)
  386. # print("======")
  387. repairTable(inner_table)
  388. head_list = sliceTable(inner_table)
  389. return inner_table,head_list
  390. def set_head_model(inner_table):
  391. origin_inner_table = copy.deepcopy(inner_table)
  392. for i in range(len(inner_table)):
  393. for j in range(len(inner_table[i])):
  394. # 删掉单格前后符号,以免影响表头预测
  395. col = inner_table[i][j][0]
  396. col = re.sub("^[^\u4e00-\u9fa5a-zA-Z0-9]+", "", col)
  397. col = re.sub("[^\u4e00-\u9fa5a-zA-Z0-9]+$", "", col)
  398. inner_table[i][j] = col
  399. # 模型预测表头
  400. predict_list = predict(inner_table)
  401. # 组合结果
  402. for i in range(len(inner_table)):
  403. for j in range(len(inner_table[i])):
  404. inner_table[i][j] = [origin_inner_table[i][j][0], int(predict_list[i][j])]
  405. # 表头修正
  406. repairTable(inner_table)
  407. # 按表头分割表格
  408. head_list = sliceTable(inner_table)
  409. return inner_table, head_list
  410. def setHead_incontext(inner_table,pat_head,fix_value="~~",prob_min=0.5):
  411. data_x,data_position = getPredictor("form").getModel("context").encode(inner_table)
  412. predict_y = getPredictor("form").getModel("context").predict(data_x)
  413. for _position,_y in zip(data_position,predict_y):
  414. _w = _position[0]
  415. _h = _position[1]
  416. if _y[1]>prob_min:
  417. inner_table[_h][_w][1] = 1
  418. else:
  419. inner_table[_h][_w][1] = 0
  420. _item = inner_table[_h][_w][0]
  421. if re.search(pat_head,_item) is not None and len(_item)<8:
  422. inner_table[_h][_w][1] = 1
  423. # print("=====")
  424. # for item in inner_table:
  425. # print(item)
  426. # print("======")
  427. height = len(inner_table)
  428. width = len(inner_table[0])
  429. for i in range(height):
  430. for j in range(width):
  431. if re.search("[::]$", inner_table[i][j][0]) and len(inner_table[i][j][0])<8:
  432. inner_table[i][j][1] = 1
  433. repairTable(inner_table)
  434. head_list = sliceTable(inner_table)
  435. # print("inner_table:",inner_table)
  436. return inner_table,head_list
  437. #设置表头
  438. def setHead_inline(inner_table,prob_min=0.64):
  439. pad_row = "@@"
  440. pad_col = "##"
  441. removePadding(inner_table, pad_row, pad_col)
  442. pad_pattern = re.compile(pad_row+"|"+pad_col)
  443. height = len(inner_table)
  444. width = len(inner_table[0])
  445. head_list = []
  446. head_list.append(0)
  447. #行表头
  448. is_head_last = False
  449. for i in range(height):
  450. is_head = False
  451. is_long_value = False
  452. #判断是否是全padding值
  453. is_same_value = True
  454. same_value = inner_table[i][0][0]
  455. for j in range(width):
  456. if inner_table[i][j][0]!=same_value and inner_table[i][j][0]!=pad_row:
  457. is_same_value = False
  458. break
  459. #predict is head or not with model
  460. temp_item = ""
  461. for j in range(width):
  462. temp_item += inner_table[i][j][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. #print(temp_item,form_prob)
  471. if len(inner_table[i][0][0])>40:
  472. is_long_value = True
  473. if is_head or is_long_value or is_same_value:
  474. #不把连续表头分开
  475. if not is_head_last:
  476. head_list.append(i)
  477. if is_long_value or is_same_value:
  478. head_list.append(i+1)
  479. if is_head:
  480. for j in range(width):
  481. inner_table[i][j][1] = 1
  482. is_head_last = is_head
  483. head_list.append(height)
  484. #列表头
  485. for i in range(len(head_list)-1):
  486. head_begin = head_list[i]
  487. head_end = head_list[i+1]
  488. #最后一列不设置为列表头
  489. for i in range(width-1):
  490. is_head = False
  491. #predict is head or not with model
  492. temp_item = ""
  493. for j in range(head_begin,head_end):
  494. temp_item += inner_table[j][i][0]+"|"
  495. temp_item = re.sub(pad_pattern,"",temp_item)
  496. form_prob = getPredictor("form").predict(formEncoding(temp_item,expand=True),type="line")
  497. if form_prob is not None:
  498. if form_prob[0][1]>prob_min:
  499. is_head = True
  500. else:
  501. is_head = False
  502. if is_head:
  503. for j in range(head_begin,head_end):
  504. inner_table[j][i][1] = 2
  505. addPadding(inner_table, pad_row, pad_col)
  506. return inner_table,head_list
  507. #设置表头
  508. def setHead_withRule(inner_table,pattern,pat_value,count):
  509. height = len(inner_table)
  510. width = len(inner_table[0])
  511. head_list = []
  512. head_list.append(0)
  513. #行表头
  514. is_head_last = False
  515. for i in range(height):
  516. set_match = set()
  517. is_head = False
  518. is_long_value = False
  519. is_same_value = True
  520. same_value = inner_table[i][0][0]
  521. for j in range(width):
  522. if inner_table[i][j][0]!=same_value:
  523. is_same_value = False
  524. break
  525. for j in range(width):
  526. if re.search(pat_value,inner_table[i][j][0]) is not None:
  527. is_head = False
  528. break
  529. str_find = re.findall(pattern,inner_table[i][j][0])
  530. if len(str_find)>0:
  531. set_match.add(inner_table[i][j][0])
  532. if len(set_match)>=count:
  533. is_head = True
  534. if len(inner_table[i][0][0])>40:
  535. is_long_value = True
  536. if is_head or is_long_value or is_same_value:
  537. if not is_head_last:
  538. head_list.append(i)
  539. if is_head:
  540. for j in range(width):
  541. inner_table[i][j][1] = 1
  542. is_head_last = is_head
  543. head_list.append(height)
  544. #列表头
  545. for i in range(len(head_list)-1):
  546. head_begin = head_list[i]
  547. head_end = head_list[i+1]
  548. #最后一列不设置为列表头
  549. for i in range(width-1):
  550. set_match = set()
  551. is_head = False
  552. for j in range(head_begin,head_end):
  553. if re.search(pat_value,inner_table[j][i][0]) is not None:
  554. is_head = False
  555. break
  556. str_find = re.findall(pattern,inner_table[j][i][0])
  557. if len(str_find)>0:
  558. set_match.add(inner_table[j][i][0])
  559. if len(set_match)>=count:
  560. is_head = True
  561. if is_head:
  562. for j in range(head_begin,head_end):
  563. inner_table[j][i][1] = 2
  564. return inner_table,head_list
  565. #取得表格的处理方向
  566. def getDirect(inner_table,begin,end):
  567. '''
  568. column_head = set()
  569. row_head = set()
  570. widths = len(inner_table[0])
  571. for height in range(begin,end):
  572. for width in range(widths):
  573. if inner_table[height][width][1] ==1:
  574. row_head.add(height)
  575. if inner_table[height][width][1] ==2:
  576. column_head.add(width)
  577. company_pattern = re.compile("公司")
  578. if 0 in column_head and begin not in row_head:
  579. return "column"
  580. if 0 in column_head and begin in row_head:
  581. for height in range(begin,end):
  582. count = 0
  583. count_flag = True
  584. for width_index in range(width):
  585. if inner_table[height][width_index][1]==0:
  586. if re.search(company_pattern,inner_table[height][width_index][0]) is not None:
  587. count += 1
  588. else:
  589. count_flag = False
  590. if count_flag and count>=2:
  591. return "column"
  592. return "row"
  593. '''
  594. count_row_keys = 0
  595. count_column_keys = 0
  596. width = len(inner_table[0])
  597. if begin<end:
  598. for w in range(len(inner_table[begin])):
  599. if inner_table[begin][w][1]!=0:
  600. count_row_keys += 1
  601. for h in range(begin,end):
  602. if inner_table[h][0][1]!=0:
  603. count_column_keys += 1
  604. company_pattern = re.compile("有限(责任)?公司")
  605. for height in range(begin,end):
  606. count_set = set()
  607. count_flag = True
  608. for width_index in range(width):
  609. if inner_table[height][width_index][1]==0:
  610. if re.search(company_pattern,inner_table[height][width_index][0]) is not None:
  611. count_set.add(inner_table[height][width_index][0])
  612. else:
  613. count_flag = False
  614. if count_flag and len(count_set)>=2:
  615. return "column"
  616. # if count_column_keys>count_row_keys: #2022/2/15 此项不够严谨,造成很多错误,故取消
  617. # return "column"
  618. return "row"
  619. #根据表格处理方向生成句子,
  620. def getTableText(inner_table,head_list,key_direct=False):
  621. # packPattern = "(标包|[标包][号段名])"
  622. packPattern = "(标包|标的|[标包][号段名]|((项目|物资|设备|场次|标段|标的|产品)(名称)))" # 2020/11/23 大网站规则,补充采购类包名
  623. rankPattern = "(排名|排序|名次|序号|评标结果|评审结果|是否中标|推荐意见)" # 2020/11/23 大网站规则,添加序号为排序
  624. entityPattern = "((候选|[中投]标|报价)(单位|公司|人|供应商))|供应商名称"
  625. moneyPattern = "([中投]标|报价)(金额|价)"
  626. height = len(inner_table)
  627. width = len(inner_table[0])
  628. text = ""
  629. for head_i in range(len(head_list)-1):
  630. head_begin = head_list[head_i]
  631. head_end = head_list[head_i+1]
  632. direct = getDirect(inner_table, head_begin, head_end)
  633. #若只有一行,则直接按行读取
  634. if head_end-head_begin==1:
  635. text_line = ""
  636. for i in range(head_begin,head_end):
  637. for w in range(len(inner_table[i])):
  638. if inner_table[i][w][1]==1:
  639. _punctuation = ":"
  640. else:
  641. _punctuation = "," #2021/12/15 统一为中文标点,避免 206893924 国际F座1108,1,009,197.49元
  642. if w>0:
  643. if inner_table[i][w][0]!= inner_table[i][w-1][0]:
  644. text_line += inner_table[i][w][0]+_punctuation
  645. else:
  646. text_line += inner_table[i][w][0]+_punctuation
  647. text_line = text_line+"。" if text_line!="" else text_line
  648. text += text_line
  649. else:
  650. #构建一个共现矩阵
  651. table_occurence = []
  652. for i in range(head_begin,head_end):
  653. line_oc = []
  654. for j in range(width):
  655. cell = inner_table[i][j]
  656. line_oc.append({"text":cell[0],"type":cell[1],"occu_count":0,"left_head":"","top_head":"","left_dis":0,"top_dis":0})
  657. table_occurence.append(line_oc)
  658. occu_height = len(table_occurence)
  659. occu_width = len(table_occurence[0]) if len(table_occurence)>0 else 0
  660. #为每个属性值寻找表头
  661. for i in range(occu_height):
  662. for j in range(occu_width):
  663. cell = table_occurence[i][j]
  664. #是属性值
  665. if cell["type"]==0 and cell["text"]!="":
  666. left_head = ""
  667. top_head = ""
  668. find_flag = False
  669. temp_head = ""
  670. for loop_i in range(1,i+1):
  671. if not key_direct:
  672. key_values = [1,2]
  673. else:
  674. key_values = [1]
  675. if table_occurence[i-loop_i][j]["type"] in key_values:
  676. if find_flag:
  677. if table_occurence[i-loop_i][j]["text"]!=temp_head:
  678. top_head = table_occurence[i-loop_i][j]["text"]+":"+top_head
  679. else:
  680. top_head = table_occurence[i-loop_i][j]["text"]+":"+top_head
  681. find_flag = True
  682. temp_head = table_occurence[i-loop_i][j]["text"]
  683. table_occurence[i-loop_i][j]["occu_count"] += 1
  684. else:
  685. #找到表头后遇到属性值就返回
  686. if find_flag:
  687. break
  688. cell["top_head"] += top_head
  689. find_flag = False
  690. temp_head = ""
  691. for loop_j in range(1,j+1):
  692. if not key_direct:
  693. key_values = [1,2]
  694. else:
  695. key_values = [2]
  696. if table_occurence[i][j-loop_j]["type"] in key_values:
  697. if find_flag:
  698. if table_occurence[i][j-loop_j]["text"]!=temp_head:
  699. left_head = table_occurence[i][j-loop_j]["text"]+":"+left_head
  700. else:
  701. left_head = table_occurence[i][j-loop_j]["text"]+":"+left_head
  702. find_flag = True
  703. temp_head = table_occurence[i][j-loop_j]["text"]
  704. table_occurence[i][j-loop_j]["occu_count"] += 1
  705. else:
  706. if find_flag:
  707. break
  708. cell["left_head"] += left_head
  709. if direct=="row":
  710. for i in range(occu_height):
  711. pack_text = ""
  712. rank_text = ""
  713. entity_text = ""
  714. text_line = ""
  715. money_text = ""
  716. #在同一句话中重复的可以去掉
  717. text_set = set()
  718. for j in range(width):
  719. cell = table_occurence[i][j]
  720. if cell["type"]==0 or (cell["type"]==1 and cell["occu_count"]==0):
  721. cell = table_occurence[i][j]
  722. head = (cell["top_head"]+":") if len(cell["top_head"])>0 else ""
  723. if re.search("单报标限总]价|金额|成交报?价|报价", head):
  724. head = cell["left_head"] + head
  725. else:
  726. head += cell["left_head"]
  727. if str(head+cell["text"]) in text_set:
  728. continue
  729. if re.search(packPattern,head) is not None:
  730. pack_text += head+cell["text"]+","
  731. elif re.search(rankPattern,head) is not None: # 2020/11/23 大网站规则发现问题,if 改elif
  732. #排名替换为同一种表达
  733. rank_text += head+cell["text"]+","
  734. #print(rank_text)
  735. elif re.search(entityPattern,head) is not None:
  736. entity_text += head+cell["text"]+","
  737. #print(entity_text)
  738. else:
  739. if re.search(moneyPattern,head) is not None and entity_text!="":
  740. money_text += head+cell["text"]+","
  741. else:
  742. text_line += head+cell["text"]+","
  743. text_set.add(str(head+cell["text"]))
  744. text += pack_text+rank_text+entity_text+money_text+text_line
  745. text = text[:-1]+"。" if len(text)>0 else text
  746. else:
  747. for j in range(occu_width):
  748. pack_text = ""
  749. rank_text = ""
  750. entity_text = ""
  751. text_line = ""
  752. text_set = set()
  753. for i in range(occu_height):
  754. cell = table_occurence[i][j]
  755. if cell["type"]==0 or (cell["type"]==1 and cell["occu_count"]==0):
  756. cell = table_occurence[i][j]
  757. head = (cell["left_head"]+"") if len(cell["left_head"])>0 else ""
  758. if re.search("单报标限总]价|金额|成交报?价|报价", head):
  759. head = cell["top_head"] + head
  760. else:
  761. head += cell["top_head"]
  762. if str(head+cell["text"]) in text_set:
  763. continue
  764. if re.search(packPattern,head) is not None:
  765. pack_text += head+cell["text"]+","
  766. elif re.search(rankPattern,head) is not None: # 2020/11/23 大网站规则发现问题,if 改elif
  767. #排名替换为同一种表达
  768. rank_text += head+cell["text"]+","
  769. #print(rank_text)
  770. elif re.search(entityPattern,head) is not None and \
  771. re.search('业绩|资格|条件',head)==None and re.search('业绩',cell["text"])==None : #2021/10/19 解决包含业绩的行调到前面问题
  772. entity_text += head+cell["text"]+","
  773. #print(entity_text)
  774. else:
  775. text_line += head+cell["text"]+","
  776. text_set.add(str(head+cell["text"]))
  777. text += pack_text+rank_text+entity_text+text_line
  778. text = text[:-1]+"。" if len(text)>0 else text
  779. # if direct=="row":
  780. # for i in range(head_begin,head_end):
  781. # pack_text = ""
  782. # rank_text = ""
  783. # entity_text = ""
  784. # text_line = ""
  785. # #在同一句话中重复的可以去掉
  786. # text_set = set()
  787. # for j in range(width):
  788. # cell = inner_table[i][j]
  789. # #是属性值
  790. # if cell[1]==0 and cell[0]!="":
  791. # head = ""
  792. #
  793. # find_flag = False
  794. # temp_head = ""
  795. # for loop_i in range(0,i+1-head_begin):
  796. # if not key_direct:
  797. # key_values = [1,2]
  798. # else:
  799. # key_values = [1]
  800. # if inner_table[i-loop_i][j][1] in key_values:
  801. # if find_flag:
  802. # if inner_table[i-loop_i][j][0]!=temp_head:
  803. # head = inner_table[i-loop_i][j][0]+":"+head
  804. # else:
  805. # head = inner_table[i-loop_i][j][0]+":"+head
  806. # find_flag = True
  807. # temp_head = inner_table[i-loop_i][j][0]
  808. # else:
  809. # #找到表头后遇到属性值就返回
  810. # if find_flag:
  811. # break
  812. #
  813. # find_flag = False
  814. # temp_head = ""
  815. #
  816. #
  817. #
  818. # for loop_j in range(1,j+1):
  819. # if not key_direct:
  820. # key_values = [1,2]
  821. # else:
  822. # key_values = [2]
  823. # if inner_table[i][j-loop_j][1] in key_values:
  824. # if find_flag:
  825. # if inner_table[i][j-loop_j][0]!=temp_head:
  826. # head = inner_table[i][j-loop_j][0]+":"+head
  827. # else:
  828. # head = inner_table[i][j-loop_j][0]+":"+head
  829. # find_flag = True
  830. # temp_head = inner_table[i][j-loop_j][0]
  831. # else:
  832. # if find_flag:
  833. # break
  834. #
  835. # if str(head+inner_table[i][j][0]) in text_set:
  836. # continue
  837. # if re.search(packPattern,head) is not None:
  838. # pack_text += head+inner_table[i][j][0]+","
  839. # elif re.search(rankPattern,head) is not None: # 2020/11/23 大网站规则发现问题,if 改elif
  840. # #排名替换为同一种表达
  841. # rank_text += head+inner_table[i][j][0]+","
  842. # #print(rank_text)
  843. # elif re.search(entityPattern,head) is not None:
  844. # entity_text += head+inner_table[i][j][0]+","
  845. # #print(entity_text)
  846. # else:
  847. # text_line += head+inner_table[i][j][0]+","
  848. # text_set.add(str(head+inner_table[i][j][0]))
  849. # text += pack_text+rank_text+entity_text+text_line
  850. # text = text[:-1]+"。" if len(text)>0 else text
  851. # else:
  852. # for j in range(width):
  853. #
  854. # rank_text = ""
  855. # entity_text = ""
  856. # text_line = ""
  857. # text_set = set()
  858. # for i in range(head_begin,head_end):
  859. # cell = inner_table[i][j]
  860. # #是属性值
  861. # if cell[1]==0 and cell[0]!="":
  862. # find_flag = False
  863. # head = ""
  864. # temp_head = ""
  865. #
  866. # for loop_j in range(1,j+1):
  867. # if not key_direct:
  868. # key_values = [1,2]
  869. # else:
  870. # key_values = [2]
  871. # if inner_table[i][j-loop_j][1] in key_values:
  872. # if find_flag:
  873. # if inner_table[i][j-loop_j][0]!=temp_head:
  874. # head = inner_table[i][j-loop_j][0]+":"+head
  875. # else:
  876. # head = inner_table[i][j-loop_j][0]+":"+head
  877. # find_flag = True
  878. # temp_head = inner_table[i][j-loop_j][0]
  879. # else:
  880. # if find_flag:
  881. # break
  882. # find_flag = False
  883. # temp_head = ""
  884. # for loop_i in range(0,i+1-head_begin):
  885. # if not key_direct:
  886. # key_values = [1,2]
  887. # else:
  888. # key_values = [1]
  889. # if inner_table[i-loop_i][j][1] in key_values:
  890. # if find_flag:
  891. # if inner_table[i-loop_i][j][0]!=temp_head:
  892. # head = inner_table[i-loop_i][j][0]+":"+head
  893. # else:
  894. # head = inner_table[i-loop_i][j][0]+":"+head
  895. # find_flag = True
  896. # temp_head = inner_table[i-loop_i][j][0]
  897. # else:
  898. # if find_flag:
  899. # break
  900. # if str(head+inner_table[i][j][0]) in text_set:
  901. # continue
  902. # if re.search(rankPattern,head) is not None:
  903. # rank_text += head+inner_table[i][j][0]+","
  904. # #print(rank_text)
  905. # elif re.search(entityPattern,head) is not None:
  906. # entity_text += head+inner_table[i][j][0]+","
  907. # #print(entity_text)
  908. # else:
  909. # text_line += head+inner_table[i][j][0]+","
  910. # text_set.add(str(head+inner_table[i][j][0]))
  911. # text += rank_text+entity_text+text_line
  912. # text = text[:-1]+"。" if len(text)>0 else text
  913. return text
  914. def removeFix(inner_table,fix_value="~~"):
  915. height = len(inner_table)
  916. width = len(inner_table[0])
  917. for h in range(height):
  918. for w in range(width):
  919. if inner_table[h][w][0]==fix_value:
  920. inner_table[h][w][0] = ""
  921. def trunTable(tbody,in_attachment):
  922. # print(tbody.find('tbody'))
  923. # 附件中的表格,排除异常错乱的表格
  924. if in_attachment:
  925. if tbody.name=='table':
  926. _tbody = tbody.find('tbody')
  927. if _tbody is None:
  928. _tbody = tbody
  929. else:
  930. _tbody = tbody
  931. _td_len_list = []
  932. for _tr in _tbody.find_all(recursive=False):
  933. len_td = len(_tr.find_all(recursive=False))
  934. _td_len_list.append(len_td)
  935. if len(list(set(_td_len_list)))>8:
  936. return None
  937. fixSpan(tbody)
  938. inner_table = getTable(tbody)
  939. inner_table = fixTable(inner_table)
  940. if len(inner_table)>0 and len(inner_table[0])>0:
  941. #inner_table,head_list = setHead_withRule(inner_table,pat_head,pat_value,3)
  942. #inner_table,head_list = setHead_inline(inner_table)
  943. # inner_table, head_list = setHead_initem(inner_table,pat_head)
  944. inner_table, head_list = set_head_model(inner_table)
  945. # inner_table,head_list = setHead_incontext(inner_table,pat_head)
  946. # print("table_head", inner_table)
  947. # print("head_list", head_list)
  948. # for begin in range(len(head_list[:-1])):
  949. # for item in inner_table[head_list[begin]:head_list[begin+1]]:
  950. # print(item)
  951. # print("====")
  952. removeFix(inner_table)
  953. # print("----")
  954. # print(head_list)
  955. # for item in inner_table:
  956. # print(item)
  957. tbody.string = getTableText(inner_table,head_list)
  958. table_max_len = 30000
  959. tbody.string = tbody.string[:table_max_len]
  960. #print(tbody.string)
  961. tbody.name = "turntable"
  962. return inner_table
  963. return None
  964. pat_head = re.compile('^(名称|序号|项目|标项|工程|品目[一二三四1234]|第[一二三四1234](标段|名|候选人|中标)|包段|标包|分包|包号|货物|单位|数量|价格|报价|金额|总价|单价|[招投中]标|候选|编号|得分|评委|评分|名次|排名|排序|科室|方式|工期|时间|产品|开始|结束|联系|日期|面积|姓名|证号|备注|级别|地[点址]|类型|代理|制造|企业资质|质量目标|工期目标|(需求|服务|项目|施工|采购|招租|出租|转让|出让|业主|询价|委托|权属|招标|竞得|抽取|承建)(人|方|单位)(名称)?|(供应商|供货商|服务商)(名称)?)$')
  965. #pat_head = re.compile('(名称|序号|项目|工程|品目[一二三四1234]|第[一二三四1234](标段|候选人|中标)|包段|包号|货物|单位|数量|价格|报价|金额|总价|单价|[招投中]标|供应商|候选|编号|得分|评委|评分|名次|排名|排序|科室|方式|工期|时间|产品|开始|结束|联系|日期|面积|姓名|证号|备注|级别|地[点址]|类型|代理)')
  966. pat_value = re.compile("(\d{2,}.\d{1}|\d+年\d+月|\d{8,}|\d{3,}-\d{6,}|有限[责任]*公司|^\d+$)")
  967. list_innerTable = []
  968. # 2022/2/9 删除干扰标签
  969. for tag in soup.find_all('option'): #例子: 216661412
  970. if 'selected' not in tag.attrs:
  971. tag.extract()
  972. for ul in soup.find_all('ul'): #例子 156439663 多个不同channel 类别的标题
  973. if ul.find_all('li') == ul.findChildren(recursive=False) and len(set(re.findall(
  974. '招标公告|中标结果公示|中标候选人公示|招标答疑|开标评标|合同履?约?公示|开标评标|资格评审',
  975. ul.get_text(), re.S)))>3:
  976. ul.extract()
  977. # tbodies = soup.find_all('table')
  978. # 遍历表格中的每个tbody
  979. tbodies = []
  980. in_attachment = False
  981. for _part in soup.find_all():
  982. if _part.name=='table':
  983. tbodies.append((_part,in_attachment))
  984. elif _part.name=='div':
  985. if 'class' in _part.attrs and "richTextFetch" in _part['class']:
  986. in_attachment = True
  987. #逆序处理嵌套表格
  988. for tbody_index in range(1,len(tbodies)+1):
  989. tbody,_in_attachment = tbodies[len(tbodies)-tbody_index]
  990. inner_table = trunTable(tbody,_in_attachment)
  991. list_innerTable.append(inner_table)
  992. # tbodies = soup.find_all('tbody')
  993. # 遍历表格中的每个tbody
  994. tbodies = []
  995. in_attachment = False
  996. for _part in soup.find_all():
  997. if _part.name == 'tbody':
  998. tbodies.append((_part, in_attachment))
  999. elif _part.name == 'div':
  1000. if 'class' in _part.attrs and "richTextFetch" in _part['class']:
  1001. in_attachment = True
  1002. #逆序处理嵌套表格
  1003. for tbody_index in range(1,len(tbodies)+1):
  1004. tbody,_in_attachment = tbodies[len(tbodies)-tbody_index]
  1005. inner_table = trunTable(tbody,_in_attachment)
  1006. list_innerTable.append(inner_table)
  1007. return soup
  1008. # return list_innerTable
  1009. re_num = re.compile("[二三四五六七八九]十[一二三四五六七八九]?|十[一二三四五六七八九]|[一二三四五六七八九十]")
  1010. num_dict = {
  1011. "一": 1, "二": 2,
  1012. "三": 3, "四": 4,
  1013. "五": 5, "六": 6,
  1014. "七": 7, "八": 8,
  1015. "九": 9, "十": 10}
  1016. # 一百以内的中文大写转换为数字
  1017. def change2num(text):
  1018. result_num = -1
  1019. # text = text[:6]
  1020. match = re_num.search(text)
  1021. if match:
  1022. _num = match.group()
  1023. if num_dict.get(_num):
  1024. return num_dict.get(_num)
  1025. else:
  1026. tenths = 1
  1027. the_unit = 0
  1028. num_split = _num.split("十")
  1029. if num_dict.get(num_split[0]):
  1030. tenths = num_dict.get(num_split[0])
  1031. if num_dict.get(num_split[1]):
  1032. the_unit = num_dict.get(num_split[1])
  1033. result_num = tenths * 10 + the_unit
  1034. elif re.search("\d{1,2}",text):
  1035. _num = re.search("\d{1,2}",text).group()
  1036. result_num = int(_num)
  1037. return result_num
  1038. #大纲分段处理
  1039. def get_preprocessed_outline(soup):
  1040. pattern_0 = re.compile("^(?:[二三四五六七八九]十[一二三四五六七八九]?|十[一二三四五六七八九]|[一二三四五六七八九十])[、.\.]")
  1041. pattern_1 = re.compile("^[\((]?(?:[二三四五六七八九]十[一二三四五六七八九]?|十[一二三四五六七八九]|[一二三四五六七八九十])[\))]")
  1042. pattern_2 = re.compile("^\d{1,2}[、.\.](?=[^\d]{1,2}|$)")
  1043. pattern_3 = re.compile("^[\((]?\d{1,2}[\))]")
  1044. pattern_list = [pattern_0, pattern_1, pattern_2, pattern_3]
  1045. body = soup.find("body")
  1046. if body == None:
  1047. return soup # 修复 无body的报错 例子:264419050
  1048. body_child = body.find_all(recursive=False)
  1049. deal_part = body
  1050. # print(body_child[0]['id'])
  1051. if 'id' in body_child[0].attrs:
  1052. if len(body_child) <= 2 and body_child[0]['id'] == 'pcontent':
  1053. deal_part = body_child[0]
  1054. if len(deal_part.find_all(recursive=False))>2:
  1055. deal_part = deal_part.parent
  1056. skip_tag = ['turntable', 'tbody', 'th', 'tr', 'td', 'table','thead','tfoot']
  1057. for part in deal_part.find_all(recursive=False):
  1058. # 查找解析文本的主干部分
  1059. is_main_text = False
  1060. through_text_num = 0
  1061. while (not is_main_text and part.find_all(recursive=False)):
  1062. while len(part.find_all(recursive=False)) == 1 and part.get_text(strip=True) == \
  1063. part.find_all(recursive=False)[0].get_text(strip=True):
  1064. part = part.find_all(recursive=False)[0]
  1065. max_len = len(part.get_text(strip=True))
  1066. is_main_text = True
  1067. for t_part in part.find_all(recursive=False):
  1068. if t_part.name not in skip_tag and t_part.get_text(strip=True)!="":
  1069. through_text_num += 1
  1070. if t_part.get_text(strip=True)!="" and len(t_part.get_text(strip=True))/max_len>=0.65:
  1071. if t_part.name not in skip_tag:
  1072. is_main_text = False
  1073. part = t_part
  1074. break
  1075. else:
  1076. while len(t_part.find_all(recursive=False)) == 1 and t_part.get_text(strip=True) == \
  1077. t_part.find_all(recursive=False)[0].get_text(strip=True):
  1078. t_part = t_part.find_all(recursive=False)[0]
  1079. if through_text_num>2:
  1080. is_table = True
  1081. for _t_part in t_part.find_all(recursive=False):
  1082. if _t_part.name not in skip_tag:
  1083. is_table = False
  1084. break
  1085. if not is_table:
  1086. is_main_text = False
  1087. part = t_part
  1088. break
  1089. else:
  1090. is_main_text = False
  1091. part = t_part
  1092. break
  1093. is_find = False
  1094. for _pattern in pattern_list:
  1095. last_index = 0
  1096. handle_list = []
  1097. for _part in part.find_all(recursive=False):
  1098. if _part.name not in skip_tag and _part.get_text(strip=True) != "":
  1099. # print('text:', _part.get_text(strip=True))
  1100. re_match = re.search(_pattern, _part.get_text(strip=True))
  1101. if re_match:
  1102. outline_index = change2num(re_match.group())
  1103. if last_index < outline_index:
  1104. # _part.insert_before("##split##")
  1105. handle_list.append(_part)
  1106. last_index = outline_index
  1107. if len(handle_list)>1:
  1108. is_find = True
  1109. for _part in handle_list:
  1110. _part.insert_before("##split##")
  1111. if is_find:
  1112. break
  1113. # print(soup)
  1114. return soup
  1115. #数据清洗
  1116. def segment(soup,final=True):
  1117. # print("==")
  1118. # print(soup)
  1119. # print("====")
  1120. #segList = ["tr","div","h1", "h2", "h3", "h4", "h5", "h6", "header"]
  1121. subspaceList = ["td",'a',"span","p"]
  1122. if soup.name in subspaceList:
  1123. #判断有值叶子节点数
  1124. _count = 0
  1125. for child in soup.find_all(recursive=True):
  1126. if child.get_text().strip()!="" and len(child.find_all())==0:
  1127. _count += 1
  1128. if _count<=1:
  1129. text = soup.get_text()
  1130. # 2020/11/24 大网站规则添加
  1131. if 'title' in soup.attrs:
  1132. if '...' in soup.get_text() and soup.get_text().strip()[:-3] in soup.attrs['title']:
  1133. text = soup.attrs['title']
  1134. _list = []
  1135. for x in re.split("\s+",text):
  1136. if x.strip()!="":
  1137. _list.append(len(x))
  1138. if len(_list)>0:
  1139. _minLength = min(_list)
  1140. if _minLength>2:
  1141. _substr = ","
  1142. else:
  1143. _substr = ""
  1144. else:
  1145. _substr = ""
  1146. text = text.replace("\r\n",",").replace("\n",",")
  1147. text = re.sub("\s+",_substr,text)
  1148. # text = re.sub("\s+","##space##",text)
  1149. return text
  1150. segList = ["title"]
  1151. commaList = ["div","br","td","p","li"]
  1152. #commaList = []
  1153. spaceList = ["span"]
  1154. tbodies = soup.find_all('tbody')
  1155. if len(tbodies) == 0:
  1156. tbodies = soup.find_all('table')
  1157. # 递归遍历所有节点,插入符号
  1158. for child in soup.find_all(recursive=True):
  1159. # print(child.name,child.get_text())
  1160. if child.name in segList:
  1161. child.insert_after("。")
  1162. if child.name in commaList:
  1163. child.insert_after(",")
  1164. # if child.name == 'div' and 'class' in child.attrs:
  1165. # # 添加附件"attachment"标识
  1166. # if "richTextFetch" in child['class']:
  1167. # child.insert_before("##attachment##")
  1168. # print(child.parent)
  1169. # if child.name in subspaceList:
  1170. # child.insert_before("#subs"+str(child.name)+"#")
  1171. # child.insert_after("#sube"+str(child.name)+"#")
  1172. # if child.name in spaceList:
  1173. # child.insert_after(" ")
  1174. text = str(soup.get_text())
  1175. #替换英文冒号为中文冒号
  1176. text = re.sub("(?<=[\u4e00-\u9fa5]):|:(?=[\u4e00-\u9fa5])",":",text)
  1177. #替换为中文逗号
  1178. text = re.sub("(?<=[\u4e00-\u9fa5]),|,(?=[\u4e00-\u9fa5])",",",text)
  1179. #替换为中文分号
  1180. text = re.sub("(?<=[\u4e00-\u9fa5]);|;(?=[\u4e00-\u9fa5])",";",text)
  1181. # 感叹号替换为中文句号
  1182. text = re.sub("(?<=[\u4e00-\u9fa5])[!!]|[!!](?=[\u4e00-\u9fa5])","。",text)
  1183. #替换格式未识别的问号为" " ,update:2021/7/20
  1184. text = re.sub("[?\?]{2,}"," ",text)
  1185. #替换"""为"“",否则导入deepdive出错
  1186. # text = text.replace('"',"“").replace("\r","").replace("\n",",")
  1187. text = text.replace('"',"“").replace("\r","").replace("\n","") #2022/1/4修复 非分段\n 替换为逗号造成 公司拆分 span \n南航\n上海\n分公司
  1188. # print('==1',text)
  1189. # text = re.sub("\s{4,}",",",text)
  1190. # 解决公告中的" "空格替换问题
  1191. if re.search("\s{4,}",text):
  1192. _text = ""
  1193. for _sent in re.split("。+",text):
  1194. for _sent2 in re.split(',+',_sent):
  1195. for _sent3 in re.split(":+",_sent2):
  1196. for _t in re.split("\s{4,}",_sent3):
  1197. if len(_t)<3:
  1198. _text += _t
  1199. else:
  1200. _text += ","+_t
  1201. _text += ":"
  1202. _text = _text[:-1]
  1203. _text += ","
  1204. _text = _text[:-1]
  1205. _text += "。"
  1206. _text = _text[:-1]
  1207. text = _text
  1208. # print('==2',text)
  1209. #替换标点
  1210. #替换连续的标点
  1211. if final:
  1212. text = re.sub("##space##"," ",text)
  1213. punc_pattern = "(?P<del>[。,;::,\s]+)"
  1214. list_punc = re.findall(punc_pattern,text)
  1215. list_punc.sort(key=lambda x:len(x),reverse=True)
  1216. for punc_del in list_punc:
  1217. if len(punc_del)>1:
  1218. if len(punc_del.strip())>0:
  1219. if ":" in punc_del.strip():
  1220. if "。" in punc_del.strip():
  1221. text = re.sub(punc_del, ":。", text)
  1222. else:
  1223. text = re.sub(punc_del,":",text)
  1224. else:
  1225. text = re.sub(punc_del,punc_del.strip()[0],text) #2021/12/09 修正由于某些标签后插入符号把原来符号替换
  1226. else:
  1227. text = re.sub(punc_del,"",text)
  1228. #将连续的中文句号替换为一个
  1229. text_split = text.split("。")
  1230. text_split = [x for x in text_split if len(x)>0]
  1231. text = "。".join(text_split)
  1232. # #删除标签中的所有空格
  1233. # for subs in subspaceList:
  1234. # patten = "#subs"+str(subs)+"#(.*?)#sube"+str(subs)+"#"
  1235. # while(True):
  1236. # oneMatch = re.search(re.compile(patten),text)
  1237. # if oneMatch is not None:
  1238. # _match = oneMatch.group(1)
  1239. # text = text.replace("#subs"+str(subs)+"#"+_match+"#sube"+str(subs)+"#",_match)
  1240. # else:
  1241. # break
  1242. # text过大报错
  1243. LOOP_LEN = 10000
  1244. LOOP_BEGIN = 0
  1245. _text = ""
  1246. if len(text)<10000000:
  1247. while(LOOP_BEGIN<len(text)):
  1248. _text += re.sub(")",")",re.sub("(","(",re.sub("\s+","",text[LOOP_BEGIN:LOOP_BEGIN+LOOP_LEN])))
  1249. LOOP_BEGIN += LOOP_LEN
  1250. text = _text
  1251. # 附件标识前修改为句号,避免正文和附件内容混合在一起
  1252. text = re.sub("[^。](?=##attachment##)","。",text)
  1253. text = re.sub("[^。](?=##attachment_begin##)","。",text)
  1254. text = re.sub("[^。](?=##attachment_end##)","。",text)
  1255. text = re.sub("##attachment_begin##。","##attachment_begin##",text)
  1256. text = re.sub("##attachment_end##。","##attachment_end##",text)
  1257. return text
  1258. '''
  1259. #数据清洗
  1260. def segment(soup):
  1261. segList = ["title"]
  1262. commaList = ["p","div","h1", "h2", "h3", "h4", "h5", "h6", "header", "dl", "ul", "label"]
  1263. spaceList = ["span"]
  1264. tbodies = soup.find_all('tbody')
  1265. if len(tbodies) == 0:
  1266. tbodies = soup.find_all('table')
  1267. # 递归遍历所有节点,插入符号
  1268. for child in soup.find_all(recursive=True):
  1269. if child.name == 'br':
  1270. child.insert_before(',')
  1271. child_text = re.sub('\s', '', child.get_text())
  1272. if child_text == '' or child_text[-1] in ['。',',',':',';']:
  1273. continue
  1274. if child.name in segList:
  1275. child.insert_after("。")
  1276. if child.name in commaList:
  1277. if len(child_text)>3 and len(child_text) <50: # 先判断是否字数少于50,成立加逗号,否则加句号
  1278. child.insert_after(",")
  1279. elif len(child_text) >=50:
  1280. child.insert_after("。")
  1281. #if child.name in spaceList:
  1282. #child.insert_after(" ")
  1283. text = str(soup.get_text())
  1284. text = re.sub("\s{5,}",",",text)
  1285. text = text.replace('"',"“").replace("\r","").replace("\n",",")
  1286. #替换"""为"“",否则导入deepdive出错
  1287. text = text.replace('"',"“")
  1288. #text = text.replace('"',"“").replace("\r","").replace("\n","")
  1289. #删除所有空格
  1290. text = re.sub("\s+","#nbsp#",text)
  1291. text_list = text.split('#nbsp#')
  1292. new_text = ''
  1293. for i in range(len(text_list)-1):
  1294. if text_list[i] == '' or text_list[i][-1] in [',','。',';',':']:
  1295. new_text += text_list[i]
  1296. elif re.findall('([一二三四五六七八九]、)', text_list[i+1][:4]) != []:
  1297. new_text += text_list[i] + '。'
  1298. elif re.findall('([0-9]、)', text_list[i+1][:4]) != []:
  1299. new_text += text_list[i] + ';'
  1300. elif text_list[i].isdigit() and text_list[i+1].isdigit():
  1301. new_text += text_list[i] + ' '
  1302. elif text_list[i][-1] in ['-',':','(',')','/','(',')','——','年','月','日','时','分','¥'] or text_list[i+1][0] in ['-',':','(',')','/','(',')','——','年','月','日','时','分','元','万元']:
  1303. new_text += text_list[i]
  1304. elif len(text_list[i]) >= 3 and len(text_list[i+1]) >= 3:
  1305. new_text += text_list[i] + ','
  1306. else:
  1307. new_text += text_list[i]
  1308. new_text += text_list[-1]
  1309. text = new_text
  1310. #替换英文冒号为中文冒号
  1311. text = re.sub("(?<=[\u4e00-\u9fa5]):|:(?=[\u4e00-\u9fa5])",":",text)
  1312. #替换为中文逗号
  1313. text = re.sub("(?<=[\u4e00-\u9fa5]),|,(?=[\u4e00-\u9fa5])",",",text)
  1314. #替换为中文分号
  1315. text = re.sub("(?<=[\u4e00-\u9fa5]);|;(?=[\u4e00-\u9fa5])",";",text)
  1316. #替换标点
  1317. while(True):
  1318. #替换连续的标点
  1319. punc = re.search(",(?P<punc>:|。|,|;)\s*",text)
  1320. if punc is not None:
  1321. text = re.sub(","+punc.group("punc")+"\s*",punc.group("punc"),text)
  1322. punc = re.search("(?P<punc>:|。|,|;)\s*,",text)
  1323. if punc is not None:
  1324. text = re.sub(punc.group("punc")+"\s*,",punc.group("punc"),text)
  1325. else:
  1326. #替换标点之后的空格
  1327. punc = re.search("(?P<punc>:|。|,|;)\s+",text)
  1328. if punc is not None:
  1329. text = re.sub(punc.group("punc")+"\s+",punc.group("punc"),text)
  1330. else:
  1331. break
  1332. #将连续的中文句号替换为一个
  1333. text_split = text.split("。")
  1334. text_split = [x for x in text_split if len(x)>0]
  1335. text = "。".join(text_split)
  1336. #替换中文括号为英文括号
  1337. text = re.sub("(","(",text)
  1338. text = re.sub(")",")",text)
  1339. return text
  1340. '''
  1341. #连续实体合并(弃用)
  1342. def union_ner(list_ner):
  1343. result_list = []
  1344. union_index = []
  1345. union_index_set = set()
  1346. for i in range(len(list_ner)-1):
  1347. if len(set([str(list_ner[i][2]),str(list_ner[i+1][2])])&set(["org","company"]))==2:
  1348. if list_ner[i][1]-list_ner[i+1][0]==1:
  1349. union_index_set.add(i)
  1350. union_index_set.add(i+1)
  1351. union_index.append((i,i+1))
  1352. for i in range(len(list_ner)):
  1353. if i not in union_index_set:
  1354. result_list.append(list_ner[i])
  1355. for item in union_index:
  1356. #print(str(list_ner[item[0]][3])+str(list_ner[item[1]][3]))
  1357. 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])))
  1358. return result_list
  1359. # def get_preprocessed(articles,useselffool=False):
  1360. # '''
  1361. # @summary:预处理步骤,NLP处理、实体识别
  1362. # @param:
  1363. # articles:待处理的文章list [[id,source,jointime,doc_id,title]]
  1364. # @return:list of articles,list of each article of sentences,list of each article of entitys
  1365. # '''
  1366. # list_articles = []
  1367. # list_sentences = []
  1368. # list_entitys = []
  1369. # cost_time = dict()
  1370. # for article in articles:
  1371. # list_sentences_temp = []
  1372. # list_entitys_temp = []
  1373. # doc_id = article[0]
  1374. # sourceContent = article[1]
  1375. # _send_doc_id = article[3]
  1376. # _title = article[4]
  1377. # #表格处理
  1378. # key_preprocess = "tableToText"
  1379. # start_time = time.time()
  1380. # article_processed = segment(tableToText(BeautifulSoup(sourceContent,"lxml")))
  1381. #
  1382. # # log(article_processed)
  1383. #
  1384. # if key_preprocess not in cost_time:
  1385. # cost_time[key_preprocess] = 0
  1386. # cost_time[key_preprocess] += time.time()-start_time
  1387. #
  1388. # #article_processed = article[1]
  1389. # list_articles.append(Article(doc_id,article_processed,sourceContent,_send_doc_id,_title))
  1390. # #nlp处理
  1391. # if article_processed is not None and len(article_processed)!=0:
  1392. # split_patten = "。"
  1393. # sentences = []
  1394. # _begin = 0
  1395. # for _iter in re.finditer(split_patten,article_processed):
  1396. # sentences.append(article_processed[_begin:_iter.span()[1]])
  1397. # _begin = _iter.span()[1]
  1398. # sentences.append(article_processed[_begin:])
  1399. #
  1400. # lemmas = []
  1401. # doc_offsets = []
  1402. # dep_types = []
  1403. # dep_tokens = []
  1404. #
  1405. # time1 = time.time()
  1406. #
  1407. # '''
  1408. # tokens_all = fool.cut(sentences)
  1409. # #pos_all = fool.LEXICAL_ANALYSER.pos(tokens_all)
  1410. # #ner_tag_all = fool.LEXICAL_ANALYSER.ner_labels(sentences,tokens_all)
  1411. # ner_entitys_all = fool.ner(sentences)
  1412. # '''
  1413. # #限流执行
  1414. # key_nerToken = "nerToken"
  1415. # start_time = time.time()
  1416. # tokens_all,ner_entitys_all = getTokensAndNers(sentences,useselffool=useselffool)
  1417. # if key_nerToken not in cost_time:
  1418. # cost_time[key_nerToken] = 0
  1419. # cost_time[key_nerToken] += time.time()-start_time
  1420. #
  1421. #
  1422. # for sentence_index in range(len(sentences)):
  1423. #
  1424. #
  1425. #
  1426. # list_sentence_entitys = []
  1427. # sentence_text = sentences[sentence_index]
  1428. # tokens = tokens_all[sentence_index]
  1429. #
  1430. # list_tokenbegin = []
  1431. # begin = 0
  1432. # for i in range(0,len(tokens)):
  1433. # list_tokenbegin.append(begin)
  1434. # begin += len(str(tokens[i]))
  1435. # list_tokenbegin.append(begin+1)
  1436. # #pos_tag = pos_all[sentence_index]
  1437. # pos_tag = ""
  1438. #
  1439. # ner_entitys = ner_entitys_all[sentence_index]
  1440. #
  1441. # 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))
  1442. #
  1443. # #识别package
  1444. #
  1445. #
  1446. # #识别实体
  1447. # for ner_entity in ner_entitys:
  1448. # begin_index_temp = ner_entity[0]
  1449. # end_index_temp = ner_entity[1]
  1450. # entity_type = ner_entity[2]
  1451. # entity_text = ner_entity[3]
  1452. #
  1453. # for j in range(len(list_tokenbegin)):
  1454. # if list_tokenbegin[j]==begin_index_temp:
  1455. # begin_index = j
  1456. # break
  1457. # elif list_tokenbegin[j]>begin_index_temp:
  1458. # begin_index = j-1
  1459. # break
  1460. # begin_index_temp += len(str(entity_text))
  1461. # for j in range(begin_index,len(list_tokenbegin)):
  1462. # if list_tokenbegin[j]>=begin_index_temp:
  1463. # end_index = j-1
  1464. # break
  1465. # entity_id = "%s_%d_%d_%d"%(doc_id,sentence_index,begin_index,end_index)
  1466. #
  1467. # #去掉标点符号
  1468. # entity_text = re.sub("[,,。:]","",entity_text)
  1469. # 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))
  1470. #
  1471. #
  1472. # #使用正则识别金额
  1473. # entity_type = "money"
  1474. #
  1475. # #money_patten_str = "(([1-9][\d,,]*(?:\.\d+)?[百千万亿]?[\(\)()元整]+)|([零壹贰叁肆伍陆柒捌玖拾佰仟萬億十百千万亿元角分]{3,})|(?:[¥¥]+,?|报价|标价)[(\(]?([万])?元?[)\)]?[::]?.{,7}?([1-9][\d,,]*(?:\.\d+)?(?:,?)[百千万亿]?)|([1-9][\d,,]*(?:\.\d+)?(?:,?)[百千万亿]?)[\((]?([万元]{1,2}))*"
  1476. #
  1477. # list_money_pattern = {"cn":"(()()([零壹贰叁肆伍陆柒捌玖拾佰仟萬億十百千万亿元角分]{3,})())*",
  1478. # "key_word":"((?:[¥¥]+,?|[报标限]价|金额)(?:[(\(]?\s*([万元]*)\s*[)\)]?)\s*[::]?(\s*[^壹贰叁肆伍陆柒捌玖拾佰仟萬億分]{,7}?)([0-9][\d,,]*(?:\.\d+)?(?:,?)[百千万亿元]*)())*",
  1479. # "front_m":"((?:[(\(]?\s*([万元]+)\s*[)\)])\s*[::]?(\s*[^壹贰叁肆伍陆柒捌玖拾佰仟萬億分]{,7}?)([0-9][\d,,]*(?:\.\d+)?(?:,?)[百千万亿元]*)())*",
  1480. # "behind_m":"(()()([0-9][\d,,]*(?:\.\d+)?(?:,?)[百千万亿]*)[\((]?([万元]+)[\))]?)*"}
  1481. #
  1482. # set_begin = set()
  1483. # for pattern_key in list_money_pattern.keys():
  1484. # pattern = re.compile(list_money_pattern[pattern_key])
  1485. # all_match = re.findall(pattern, sentence_text)
  1486. # index = 0
  1487. # for i in range(len(all_match)):
  1488. # if len(all_match[i][0])>0:
  1489. # # print("===",all_match[i])
  1490. # #print(all_match[i][0])
  1491. # unit = ""
  1492. # entity_text = all_match[i][3]
  1493. # if pattern_key in ["key_word","front_m"]:
  1494. # unit = all_match[i][1]
  1495. # else:
  1496. # unit = all_match[i][4]
  1497. # if entity_text.find("元")>=0:
  1498. # unit = ""
  1499. #
  1500. # index += len(all_match[i][0])-len(entity_text)-len(all_match[i][4])#-len(all_match[i][1])-len(all_match[i][2])#整个提出来的作为实体->数字部分作为整体,否则会丢失特征
  1501. #
  1502. # begin_index_temp = index
  1503. # for j in range(len(list_tokenbegin)):
  1504. # if list_tokenbegin[j]==index:
  1505. # begin_index = j
  1506. # break
  1507. # elif list_tokenbegin[j]>index:
  1508. # begin_index = j-1
  1509. # break
  1510. # index += len(str(entity_text))+len(all_match[i][4])#+len(all_match[i][2])+len(all_match[i][1])#整个提出来的作为实体
  1511. # end_index_temp = index
  1512. # #index += len(str(all_match[i][0]))
  1513. # for j in range(begin_index,len(list_tokenbegin)):
  1514. # if list_tokenbegin[j]>=index:
  1515. # end_index = j-1
  1516. # break
  1517. # entity_id = "%s_%d_%d_%d"%(doc_id,sentence_index,begin_index,end_index)
  1518. #
  1519. #
  1520. # entity_text = re.sub("[^0-9.零壹贰叁肆伍陆柒捌玖拾佰仟萬億十百千万亿元角分]","",entity_text)
  1521. # if len(unit)>0:
  1522. # entity_text = str(getUnifyMoney(entity_text)*getMultipleFactor(unit[0]))
  1523. # else:
  1524. # entity_text = str(getUnifyMoney(entity_text))
  1525. #
  1526. # _exists = False
  1527. # for item in list_sentence_entitys:
  1528. # if item.entity_id==entity_id and item.entity_type==entity_type:
  1529. # _exists = True
  1530. # if not _exists:
  1531. # if float(entity_text)>10:
  1532. # 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))
  1533. #
  1534. # else:
  1535. # index += 1
  1536. #
  1537. # list_sentence_entitys.sort(key=lambda x:x.begin_index)
  1538. # list_entitys_temp = list_entitys_temp+list_sentence_entitys
  1539. # list_sentences.append(list_sentences_temp)
  1540. # list_entitys.append(list_entitys_temp)
  1541. # return list_articles,list_sentences,list_entitys,cost_time
  1542. def get_preprocessed(articles, useselffool=False):
  1543. '''
  1544. @summary:预处理步骤,NLP处理、实体识别
  1545. @param:
  1546. articles:待处理的文章list [[id,source,jointime,doc_id,title]]
  1547. @return:list of articles,list of each article of sentences,list of each article of entitys
  1548. '''
  1549. cost_time = dict()
  1550. list_articles = get_preprocessed_article(articles,cost_time)
  1551. list_sentences,list_outlines = get_preprocessed_sentences(list_articles,True,cost_time)
  1552. list_entitys = get_preprocessed_entitys(list_sentences,True,cost_time)
  1553. calibrateEnterprise(list_articles,list_sentences,list_entitys)
  1554. return list_articles,list_sentences,list_entitys,list_outlines,cost_time
  1555. def special_treatment(sourceContent, web_source_no):
  1556. try:
  1557. if web_source_no == 'DX000202-1':
  1558. ser = re.search('中标供应商及中标金额:【((\w{5,20}-[\d,.]+,)+)】', sourceContent)
  1559. if ser:
  1560. new = ""
  1561. l = ser.group(1).split(',')
  1562. for i in range(len(l)):
  1563. it = l[i]
  1564. if '-' in it:
  1565. role, money = it.split('-')
  1566. new += '标段%d, 中标供应商: ' % (i + 1) + role + ',中标金额:' + money + '。'
  1567. sourceContent = sourceContent.replace(ser.group(0), new, 1)
  1568. elif web_source_no == '00753-14':
  1569. body = sourceContent.find("body")
  1570. body_child = body.find_all(recursive=False)
  1571. pcontent = body
  1572. if 'id' in body_child[0].attrs:
  1573. if len(body_child) <= 2 and body_child[0]['id'] == 'pcontent':
  1574. pcontent = body_child[0]
  1575. # pcontent = sourceContent.find("div", id="pcontent")
  1576. pcontent = pcontent.find_all(recursive=False)[0]
  1577. first_table = None
  1578. for idx in range(len(pcontent.find_all(recursive=False))):
  1579. t_part = pcontent.find_all(recursive=False)[idx]
  1580. if t_part.name != "table":
  1581. break
  1582. if idx == 0:
  1583. first_table = t_part
  1584. else:
  1585. for _tr in t_part.find("tbody").find_all(recursive=False):
  1586. first_table.find("tbody").append(_tr)
  1587. t_part.clear()
  1588. elif web_source_no == 'DX008357-11':
  1589. body = sourceContent.find("body")
  1590. body_child = body.find_all(recursive=False)
  1591. pcontent = body
  1592. if 'id' in body_child[0].attrs:
  1593. if len(body_child) <= 2 and body_child[0]['id'] == 'pcontent':
  1594. pcontent = body_child[0]
  1595. # pcontent = sourceContent.find("div", id="pcontent")
  1596. pcontent = pcontent.find_all(recursive=False)[0]
  1597. error_table = []
  1598. is_error_table = False
  1599. for part in pcontent.find_all(recursive=False):
  1600. if is_error_table:
  1601. if part.name == "table":
  1602. error_table.append(part)
  1603. else:
  1604. break
  1605. if part.name == "div" and part.get_text(strip=True) == "中标候选单位:":
  1606. is_error_table = True
  1607. first_table = None
  1608. for idx in range(len(error_table)):
  1609. t_part = error_table[idx]
  1610. # if t_part.name != "table":
  1611. # break
  1612. if idx == 0:
  1613. for _tr in t_part.find("tbody").find_all(recursive=False):
  1614. if _tr.get_text(strip=True) == "":
  1615. _tr.decompose()
  1616. first_table = t_part
  1617. else:
  1618. for _tr in t_part.find("tbody").find_all(recursive=False):
  1619. if _tr.get_text(strip=True) != "":
  1620. first_table.find("tbody").append(_tr)
  1621. t_part.clear()
  1622. elif web_source_no == '18021-2':
  1623. body = sourceContent.find("body")
  1624. body_child = body.find_all(recursive=False)
  1625. pcontent = body
  1626. if 'id' in body_child[0].attrs:
  1627. if len(body_child) <= 2 and body_child[0]['id'] == 'pcontent':
  1628. pcontent = body_child[0]
  1629. # pcontent = sourceContent.find("div", id="pcontent")
  1630. td = pcontent.find_all("td")
  1631. for _td in td:
  1632. if str(_td.string).strip() == "报价金额":
  1633. _td.string = "单价"
  1634. elif web_source_no == '13740-2':
  1635. # “xxx成为成交供应商”
  1636. re_match = re.search("[^,。]+成为[^,。]*成交供应商", sourceContent)
  1637. if re_match:
  1638. sourceContent = sourceContent.replace(re_match.group(), "成交人:" + re_match.group())
  1639. elif web_source_no == '03786-10':
  1640. ser1 = re.search('中标价:([\d,.]+)', sourceContent)
  1641. ser2 = re.search('合同金额[((]万元[))]:([\d,.]+)', sourceContent)
  1642. if ser1 and ser2:
  1643. m1 = ser1.group(1).replace(',', '')
  1644. m2 = ser2.group(1).replace(',', '')
  1645. if float(m1) < 100000 and (m1.split('.')[0] == m2.split('.')[0] or m2 == '0'):
  1646. new = '中标价(万元):' + m1
  1647. sourceContent = sourceContent.replace(ser1.group(0), new, 1)
  1648. elif web_source_no=='00076-4':
  1649. ser = re.search('主要标的数量:([0-9一]+)\w{,3},主要标的单价:([\d,.]+)元?,合同金额:(.00),', sourceContent)
  1650. if ser:
  1651. num = ser.group(1).replace('一', '1')
  1652. try:
  1653. num = 1 if num == '0' else num
  1654. unit_price = ser.group(2).replace(',', '')
  1655. total_price = str(int(num) * float(unit_price))
  1656. new = '合同金额:' + total_price
  1657. sourceContent = sourceContent.replace('合同金额:.00', new, 1)
  1658. except Exception as e:
  1659. log('preprocessing.py special_treatment exception')
  1660. elif web_source_no=='DX000105-2':
  1661. if re.search("成交公示", sourceContent) and re.search(',投标人:', sourceContent) and re.search(',成交人:', sourceContent)==None:
  1662. sourceContent = sourceContent.replace(',投标人:', ',成交人:')
  1663. elif web_source_no in ['03795-1', '03795-2']:
  1664. if re.search('中标单位如下', sourceContent) and re.search(',投标人:', sourceContent) and re.search(',中标人:', sourceContent)==None:
  1665. sourceContent = sourceContent.replace(',投标人:', ',中标人:')
  1666. elif web_source_no in ['04080-3', '04080-4']:
  1667. ser = re.search('合同金额:([0-9,]+.[0-9]{3,})(.{,4})', sourceContent)
  1668. if ser and '万' not in ser.group(2):
  1669. sourceContent = sourceContent.replace('合同金额:', '合同金额(万元):')
  1670. elif web_source_no=='03761-3':
  1671. ser = re.search('中标价,([0-9]+)[.0-9]*%', sourceContent)
  1672. if ser and int(ser.group(1))>100:
  1673. sourceContent = sourceContent.replace(ser.group(0), ser.group(0)[:-1]+'元')
  1674. elif web_source_no=='00695-7':
  1675. ser = re.search('支付金额:', sourceContent)
  1676. if ser:
  1677. sourceContent = sourceContent.replace('支付金额:', '合同金额:')
  1678. elif web_source_no=='00811-8':
  1679. if re.search('是否中标:是', sourceContent) and re.search('排名:\d,', sourceContent):
  1680. sourceContent = re.sub('排名:\d,', '候选', sourceContent)
  1681. return sourceContent
  1682. except Exception as e:
  1683. log('特殊数据源: %s 预处理特别修改抛出异常: %s'%(web_source_no, e))
  1684. return sourceContent
  1685. def article_limit(soup,limit_words=30000):
  1686. sub_space = re.compile("\s+")
  1687. def soup_limit(_soup,_count,max_count=30000,max_gap=500):
  1688. """
  1689. :param _soup: soup
  1690. :param _count: 当前字数
  1691. :param max_count: 字数最大限制
  1692. :param max_gap: 超过限制后的最大误差
  1693. :return:
  1694. """
  1695. _gap = _count - max_count
  1696. _is_skip = False
  1697. next_soup = None
  1698. while len(_soup.find_all(recursive=False)) == 1 and \
  1699. _soup.get_text(strip=True) == _soup.find_all(recursive=False)[0].get_text(strip=True):
  1700. _soup = _soup.find_all(recursive=False)[0]
  1701. if len(_soup.find_all(recursive=False)) == 0:
  1702. _soup.string = str(_soup.get_text())[:max_count-_count]
  1703. _count += len(re.sub(sub_space, "", _soup.string))
  1704. _gap = _count - max_count
  1705. next_soup = None
  1706. else:
  1707. for _soup_part in _soup.find_all(recursive=False):
  1708. if not _is_skip:
  1709. _count += len(re.sub(sub_space, "", _soup_part.get_text()))
  1710. if _count >= max_count:
  1711. _gap = _count - max_count
  1712. if _gap <= max_gap:
  1713. _is_skip = True
  1714. else:
  1715. _is_skip = True
  1716. next_soup = _soup_part
  1717. _count -= len(re.sub(sub_space, "", _soup_part.get_text()))
  1718. continue
  1719. else:
  1720. _soup_part.decompose()
  1721. return _count,_gap,next_soup
  1722. text_count = 0
  1723. have_attachment = False
  1724. attachment_part = None
  1725. for child in soup.find_all(recursive=True):
  1726. if child.name == 'div' and 'class' in child.attrs:
  1727. if "richTextFetch" in child['class']:
  1728. child.insert_before("##attachment##。") # 句号分开,避免项目名称等提取
  1729. attachment_part = child
  1730. have_attachment = True
  1731. break
  1732. if not have_attachment:
  1733. # 无附件
  1734. if len(re.sub(sub_space, "", soup.get_text())) > limit_words:
  1735. text_count,gap,n_soup = soup_limit(soup,text_count,max_count=limit_words,max_gap=500)
  1736. while n_soup:
  1737. text_count, gap, n_soup = soup_limit(n_soup, text_count, max_count=limit_words, max_gap=500)
  1738. else:
  1739. # 有附件
  1740. _text = re.sub(sub_space, "", soup.get_text())
  1741. _text_split = _text.split("##attachment##")
  1742. if len(_text_split[0])>limit_words:
  1743. main_soup = attachment_part.parent
  1744. main_text = main_soup.find_all(recursive=False)[0]
  1745. text_count, gap, n_soup = soup_limit(main_text, text_count, max_count=limit_words, max_gap=500)
  1746. while n_soup:
  1747. text_count, gap, n_soup = soup_limit(n_soup, text_count, max_count=limit_words, max_gap=500)
  1748. if len(_text_split[1])>limit_words:
  1749. # attachment_html纯文本,无子结构
  1750. if len(attachment_part.find_all(recursive=False))==0:
  1751. attachment_part.string = str(attachment_part.get_text())[:limit_words]
  1752. else:
  1753. attachment_text_nums = 0
  1754. attachment_skip = False
  1755. for part in attachment_part.find_all(recursive=False):
  1756. if not attachment_skip:
  1757. last_attachment_text_nums = attachment_text_nums
  1758. attachment_text_nums = attachment_text_nums + len(re.sub(sub_space, "", part.get_text()))
  1759. if attachment_text_nums>=limit_words:
  1760. part.string = str(part.get_text())[:limit_words-last_attachment_text_nums]
  1761. attachment_skip = True
  1762. else:
  1763. part.decompose()
  1764. return soup
  1765. def attachment_filelink(soup):
  1766. have_attachment = False
  1767. attachment_part = None
  1768. for child in soup.find_all(recursive=True):
  1769. if child.name == 'div' and 'class' in child.attrs:
  1770. if "richTextFetch" in child['class']:
  1771. attachment_part = child
  1772. have_attachment = True
  1773. break
  1774. if not have_attachment:
  1775. return soup
  1776. else:
  1777. # 附件类型:图片、表格
  1778. attachment_type = re.compile("\.(?:png|jpg|jpeg|tif|bmp|xlsx|xls)$")
  1779. attachment_dict = dict()
  1780. for _attachment in attachment_part.find_all(recursive=False):
  1781. if _attachment.name == 'div' and 'filemd5' in _attachment.attrs:
  1782. # print('filemd5',_attachment['filemd5'])
  1783. attachment_dict[_attachment['filemd5']] = _attachment
  1784. # print(attachment_dict)
  1785. for child in soup.find_all(recursive=True):
  1786. if child.name == 'div' and 'class' in child.attrs:
  1787. if "richTextFetch" in child['class']:
  1788. break
  1789. if "filelink" in child.attrs and child['filelink'] in attachment_dict:
  1790. if re.search(attachment_type,str(child.string).strip()) or \
  1791. ('original' in child.attrs and re.search(attachment_type,str(child['original']).strip())) or \
  1792. ('href' in child.attrs and re.search(attachment_type,str(child['href']).strip())):
  1793. # 附件插入正文标识
  1794. child.insert_before("。##attachment_begin##")
  1795. child.insert_after("。##attachment_end##")
  1796. child.replace_with(attachment_dict[child['filelink']])
  1797. # print('格式化输出',soup.prettify())
  1798. return soup
  1799. def del_achievement(text):
  1800. if re.search('中标|成交|入围|结果|评标|开标|候选人', text[:500]) == None or re.search('业绩', text) == None:
  1801. return text
  1802. p0 = '[,。;]((\d{1,2})|\d{1,2}、)[\w、]{,8}:|((\d{1,2})|\d{1,2}、)|。' # 例子 264392818
  1803. p1 = '业绩[:,](\d、[-\w()、]{6,30}(工程|项目|勘察|设计|施工|监理|总承包|采购|更新)[\w()]{,10}[,;])+' # 例子 257717618
  1804. p2 = '(类似业绩情况:|业绩:)(\w{,20}:)?(((\d)|\d、)项目名称:[-\w(),;、\d\s:]{5,100}[;。])+' # 例子 264345826
  1805. p3 = '(投标|类似|(类似)?项目|合格|有效|企业|工程)?业绩(名称|信息|\d)?:(项目名称:)?[-\w()、]{6,50}(项目|工程|勘察|设计|施工|监理|总承包|采购|更新)'
  1806. l = []
  1807. tmp = []
  1808. for it in re.finditer(p0, text):
  1809. if it.group(0)[-3:] in ['业绩:', '荣誉:']:
  1810. if tmp != []:
  1811. del_text = text[tmp[0]:it.start()]
  1812. l.append(del_text)
  1813. tmp = []
  1814. tmp.append(it.start())
  1815. elif tmp != []:
  1816. del_text = text[tmp[0]:it.start()]
  1817. l.append(del_text)
  1818. tmp = []
  1819. if tmp != []:
  1820. del_text = text[tmp[0]:]
  1821. l.append(del_text)
  1822. for del_text in l:
  1823. text = text.replace(del_text, '')
  1824. # print('删除业绩信息:', del_text)
  1825. for rs in re.finditer(p1, text):
  1826. # print('删除业绩信息:', rs.group(0))
  1827. text = text.replace(rs.group(0), '')
  1828. for rs in re.finditer(p2, text):
  1829. # print('删除业绩信息:', rs.group(0))
  1830. text = text.replace(rs.group(0), '')
  1831. for rs in re.finditer(p3, text):
  1832. # print('删除业绩信息:', rs.group(0))
  1833. text = text.replace(rs.group(0), '')
  1834. return text
  1835. def del_tabel_achievement(soup):
  1836. if re.search('中标|成交|入围|结果|评标|开标|候选人', soup.text[:800]) == None or re.search('业绩', soup.text)==None:
  1837. return None
  1838. p1 = '中标(单位|候选人)的?(企业|项目|项目负责人|\w{,5})?业绩|类似(项目)?业绩|\w{,10}业绩$|业绩(公示|情况|荣誉)'
  1839. '''删除前面标签 命中业绩规则;当前标签为表格且公布业绩相关信息的去除'''
  1840. for tag in soup.find_all('table'):
  1841. pre_text = tag.findPreviousSibling().text.strip() if tag.findPreviousSibling() != None else ""
  1842. tr_text = tag.find('tr').text.strip() if tag.find('tr') != None else ""
  1843. # print(re.search(p1, pre_text),pre_text, len(pre_text), re.findall('序号|中标候选人名称|项目名称|工程名称|合同金额|建设单位|业主', tr_text))
  1844. if re.search(p1, pre_text) and len(pre_text) < 20 and tag.find('tr') != None and len(tr_text)<100:
  1845. _count = 0
  1846. for td in tag.find('tr').find_all('td'):
  1847. td_text = td.text.strip()
  1848. if len(td_text) > 25:
  1849. break
  1850. if len(td_text) < 25 and re.search('中标候选人|(项目|业绩|工程)名称|\w{,10}业绩$|合同金额|建设单位|采购单位|业主|甲方', td_text):
  1851. _count += 1
  1852. if _count >=2:
  1853. pre_tag = tag.findPreviousSibling().extract()
  1854. del_tag = tag.extract()
  1855. # print('删除表格业绩内容', pre_tag.text + del_tag.text)
  1856. break
  1857. elif re.search('业绩名称', tr_text) and re.search('建设单位|采购单位|业主', tr_text) and len(tr_text)<100:
  1858. del_tag = tag.extract()
  1859. # print('删除表格业绩内容', del_tag.text)
  1860. del_trs = []
  1861. '''删除表格某些行公布的业绩信息'''
  1862. for tag in soup.find_all('table'):
  1863. text = tag.text
  1864. if re.search('业绩', text) == None:
  1865. continue
  1866. # for tr in tag.find_all('tr'):
  1867. trs = tag.find_all('tr')
  1868. i = 0
  1869. while i < len(trs):
  1870. tr = trs[i]
  1871. if len(tr.find_all('td'))==2 and tr.td!=None and tr.td.findNextSibling()!=None:
  1872. td1_text =tr.td.text
  1873. td2_text =tr.td.findNextSibling().text
  1874. if re.search('业绩', td1_text)!=None and len(td1_text)<10 and len(re.findall('(\d、|(\d))?[-\w()、]+(工程|项目|勘察|设计|施工|监理|总承包|采购|更新)', td2_text))>=2:
  1875. # del_tag = tr.extract()
  1876. # print('删除表格业绩内容', del_tag.text)
  1877. del_trs.append(tr)
  1878. elif tr.td != None and re.search('^业绩|业绩$', tr.td.text.strip()) and len(tr.td.text.strip())<25:
  1879. rows = tr.td.attrs.get('rowspan', '')
  1880. cols = tr.td.attrs.get('colspan', '')
  1881. if rows.isdigit() and int(rows)>2:
  1882. for j in range(int(rows)):
  1883. if i+j < len(trs):
  1884. del_trs.append(trs[i+j])
  1885. i += j
  1886. elif cols.isdigit() and int(cols)>3 and len(tr.find_all('td'))==1 and i+2 < len(trs):
  1887. next_tr_cols = 0
  1888. td_num = 0
  1889. for td in trs[i+1].find_all('td'):
  1890. td_num += 1
  1891. if td.attrs.get('colspan', '').isdigit():
  1892. next_tr_cols += int(td.attrs.get('colspan', ''))
  1893. if next_tr_cols == int(cols):
  1894. del_trs.append(tr)
  1895. for j in range(1,len(trs)-i):
  1896. if len(trs[i+j].find_all('td')) == 1:
  1897. break
  1898. elif len(trs[i+j].find_all('td')) >= td_num-1:
  1899. del_trs.append(trs[i+j])
  1900. else:
  1901. break
  1902. i += j
  1903. i += 1
  1904. for tr in del_trs:
  1905. del_tag = tr.extract()
  1906. # print('删除表格业绩内容', del_tag.text)
  1907. def get_preprocessed_article(articles,cost_time = dict(),useselffool=True):
  1908. '''
  1909. :param articles: 待处理的article source html
  1910. :param useselffool: 是否使用selffool
  1911. :return: list_articles
  1912. '''
  1913. list_articles = []
  1914. for article in articles:
  1915. doc_id = article[0]
  1916. sourceContent = article[1]
  1917. sourceContent = re.sub("<html>|</html>|<body>|</body>","",sourceContent)
  1918. sourceContent = sourceContent.replace('<br/>', '<br>')
  1919. sourceContent = re.sub("<br>(\s{0,}<br>)+","<br>",sourceContent)
  1920. # for br_match in re.findall("[^>]+?<br>",sourceContent):
  1921. # _new = re.sub("<br>","",br_match)
  1922. # # <br>标签替换为<p>标签
  1923. # if not re.search("^\s+$",_new):
  1924. # _new = '<p>'+_new + '</p>'
  1925. # # print(br_match,_new)
  1926. # sourceContent = sourceContent.replace(br_match,_new,1)
  1927. _send_doc_id = article[3]
  1928. _title = article[4]
  1929. page_time = article[5]
  1930. web_source_no = article[6]
  1931. '''特别数据源对 html 做特别修改'''
  1932. if web_source_no in ['DX000202-1']:
  1933. sourceContent = special_treatment(sourceContent, web_source_no)
  1934. #表格处理
  1935. key_preprocess = "tableToText"
  1936. start_time = time.time()
  1937. # article_processed = tableToText(BeautifulSoup(sourceContent,"lxml"))
  1938. article_processed = BeautifulSoup(sourceContent,"lxml")
  1939. '''表格业绩内容删除'''
  1940. del_tabel_achievement(article_processed)
  1941. '''特别数据源对 BeautifulSoup(html) 做特别修改'''
  1942. if web_source_no in ["00753-14","DX008357-11","18021-2"]:
  1943. article_processed = special_treatment(article_processed, web_source_no)
  1944. for _soup in article_processed.descendants:
  1945. # 识别无标签文本,添加<span>标签
  1946. if not _soup.name and not _soup.parent.string and _soup.string.strip()!="":
  1947. # print(_soup.parent.string,_soup.string.strip())
  1948. _soup.wrap(article_processed.new_tag("span"))
  1949. # print(article_processed)
  1950. # 正文和附件内容限制字数30000
  1951. article_processed = article_limit(article_processed, limit_words=30000)
  1952. # 把每个附件识别对应的html放回原来出现的位置
  1953. article_processed = attachment_filelink(article_processed)
  1954. article_processed = get_preprocessed_outline(article_processed)
  1955. # print('article_processed')
  1956. article_processed = tableToText(article_processed)
  1957. article_processed = segment(article_processed)
  1958. article_processed = article_processed.replace('(', '(').replace(')', ')') #2022/8/10 统一为中文括号
  1959. article_processed = article_processed.replace('.','.').replace('-', '-') # 2021/12/01 修正OCR识别PDF小数点错误问题
  1960. article_processed = article_processed.replace('报价限价', '招标限价') #2021/12/17 由于报价限价预测为中投标金额所以修改
  1961. article_processed = article_processed.replace('成交工程价款', '成交工程价') # 2021/12/21 修正为中标价
  1962. article_processed = re.sub('任务(?=编号[::])', '项目',article_processed) # 2022/08/10 修正为项目编号
  1963. article_processed = article_processed.replace('招标(建设)单位', '招标单位') #2022/8/10 修正预测不到表达
  1964. article_processed = re.sub("采购商(?=[^\u4e00-\u9fa5]|名称)", "招标人", article_processed)
  1965. article_processed = re.sub('(招标|采购)人(概况|信息):?[,。]', '采购人信息:', article_processed) # 2022/8/10统一表达
  1966. '''去除业绩内容'''
  1967. article_processed = del_achievement(article_processed)
  1968. # 修复OCR金额中“,”、“。”识别错误
  1969. article_processed_list = article_processed.split("##attachment##")
  1970. if len(article_processed_list)>1:
  1971. attachment_text = article_processed_list[1]
  1972. for _match in re.finditer("\d。\d{2}",attachment_text):
  1973. _match_text = _match.group()
  1974. attachment_text = attachment_text.replace(_match_text,_match_text.replace("。","."),1)
  1975. # for _match in re.finditer("(\d,\d{3})[,,.]",attachment_text):
  1976. for _match in re.finditer("\d,(?=\d{3}[^\d])",attachment_text):
  1977. _match_text = _match.group()
  1978. attachment_text = attachment_text.replace(_match_text,_match_text.replace(",",","),1)
  1979. article_processed_list[1] = attachment_text
  1980. article_processed = "##attachment##".join(article_processed_list)
  1981. '''特别数据源对 预处理后文本 做特别修改'''
  1982. if web_source_no in ['03786-10', '00076-4', 'DX000105-2', '04080-3', '04080-4', '03761-3', '00695-7',"13740-2", '00811-8', '03795-1', '03795-2']:
  1983. article_processed = special_treatment(article_processed, web_source_no)
  1984. # 提取bidway
  1985. list_bidway = extract_bidway(article_processed, _title)
  1986. if list_bidway:
  1987. bidway = list_bidway[0].get("body")
  1988. # bidway名称统一规范
  1989. bidway = bidway_integrate(bidway)
  1990. else:
  1991. bidway = ""
  1992. # 修正被","逗号分隔的时间
  1993. repair_time = re.compile("[12]\d,?\d,?\d,?[-—-―/年],?[0-1]?\d,?[-—-―/月],?[0-3]?\d,?[日号]?,?(?:上午|下午)?,?[0-2]?\d,?:,?[0-6]\d,?:,?[0-6]\d|"
  1994. "[12]\d,?\d,?\d,?[-—-―/年],?[0-1]?\d,?[-—-―/月],?[0-3]?\d,?[日号]?,?(?:上午|下午)?,?[0-2]?\d,?[:时点],?[0-6]\d分?|"
  1995. "[12]\d,?\d,?\d,?[-—-―/年],?[0-1]?\d,?[-—-―/月],?[0-3]?\d,?[日号]?,?(?:上午|下午)?,?[0-2]?\d,?[时点]|"
  1996. "[12]\d,?\d,?\d,?[-—-―/年],?[0-1]?\d,?[-—-―/月],?[0-3]?\d,?[日号]|"
  1997. "[0-2]?\d,?:,?[0-6]\d,?:,?[0-6]\d"
  1998. )
  1999. for _time in set(re.findall(repair_time,article_processed)):
  2000. if re.search(",",_time):
  2001. _time2 = re.sub(",", "", _time)
  2002. item = re.search("[12]\d{3}[-—-―/][0-1]?\d[-—-―/][0-3]\d(?=\d)", _time2)
  2003. if item:
  2004. _time2 = _time2.replace(item.group(),item.group() + " ")
  2005. article_processed = article_processed.replace(_time, _time2)
  2006. else:
  2007. item = re.search("[12]\d{3}[-—-―/][0-1]?\d[-—-―/][0-3]\d(?=\d)", _time)
  2008. if item:
  2009. _time2 = _time.replace(item.group(),item.group() + " ")
  2010. article_processed = article_processed.replace(_time, _time2)
  2011. # print('re_rtime',re.findall(repair_time,article_processed))
  2012. # log(article_processed)
  2013. if key_preprocess not in cost_time:
  2014. cost_time[key_preprocess] = 0
  2015. cost_time[key_preprocess] += round(time.time()-start_time,2)
  2016. #article_processed = article[1]
  2017. _article = Article(doc_id,article_processed,sourceContent,_send_doc_id,_title,
  2018. bidway=bidway)
  2019. _article.fingerprint = getFingerprint(_title+sourceContent)
  2020. _article.page_time = page_time
  2021. list_articles.append(_article)
  2022. return list_articles
  2023. def get_preprocessed_sentences(list_articles,useselffool=True,cost_time=dict()):
  2024. '''
  2025. :param list_articles: 经过预处理的article text
  2026. :return: list_sentences
  2027. '''
  2028. list_sentences = []
  2029. list_outlines = []
  2030. for article in list_articles:
  2031. list_sentences_temp = []
  2032. list_entitys_temp = []
  2033. doc_id = article.id
  2034. _send_doc_id = article.doc_id
  2035. _title = article.title
  2036. #表格处理
  2037. key_preprocess = "tableToText"
  2038. start_time = time.time()
  2039. article_processed = article.content
  2040. if len(_title)<100 and _title not in article_processed: # 把标题放到正文
  2041. article_processed = _title + article_processed
  2042. attachment_begin_index = -1
  2043. if key_preprocess not in cost_time:
  2044. cost_time[key_preprocess] = 0
  2045. cost_time[key_preprocess] += time.time()-start_time
  2046. #nlp处理
  2047. if article_processed is not None and len(article_processed)!=0:
  2048. split_patten = "。"
  2049. sentences = []
  2050. _begin = 0
  2051. sentences_set = set()
  2052. for _iter in re.finditer(split_patten,article_processed):
  2053. _sen = article_processed[_begin:_iter.span()[1]]
  2054. if len(_sen)>0 and _sen not in sentences_set:
  2055. # 标识在附件里的句子
  2056. if re.search("##attachment##",_sen):
  2057. attachment_begin_index = len(sentences)
  2058. # _sen = re.sub("##attachment##","",_sen)
  2059. sentences.append(_sen)
  2060. sentences_set.add(_sen)
  2061. _begin = _iter.span()[1]
  2062. _sen = article_processed[_begin:]
  2063. if re.search("##attachment##", _sen):
  2064. # _sen = re.sub("##attachment##", "", _sen)
  2065. attachment_begin_index = len(sentences)
  2066. if len(_sen)>0 and _sen not in sentences_set:
  2067. sentences.append(_sen)
  2068. sentences_set.add(_sen)
  2069. # 解析outline大纲分段
  2070. outline_list = []
  2071. if re.search("##split##",article.content):
  2072. temp_sentences = []
  2073. last_sentence_index = (-1,-1)
  2074. outline_index = 0
  2075. for sentence_index in range(len(sentences)):
  2076. sentence_text = sentences[sentence_index]
  2077. for _ in re.findall("##split##", sentence_text):
  2078. _match = re.search("##split##", sentence_text)
  2079. if last_sentence_index[0] > -1:
  2080. sentence_begin_index,wordOffset_begin = last_sentence_index
  2081. sentence_end_index = sentence_index
  2082. wordOffset_end = _match.start()
  2083. if sentence_begin_index<attachment_begin_index and sentence_end_index>=attachment_begin_index:
  2084. outline_list.append(Outline(doc_id,outline_index,'',sentence_begin_index,attachment_begin_index-1,wordOffset_begin,len(sentences[attachment_begin_index-1])))
  2085. else:
  2086. outline_list.append(Outline(doc_id,outline_index,'',sentence_begin_index,sentence_end_index,wordOffset_begin,wordOffset_end))
  2087. outline_index += 1
  2088. sentence_text = re.sub("##split##", "", sentence_text,count=1)
  2089. last_sentence_index = (sentence_index,_match.start())
  2090. temp_sentences.append(sentence_text)
  2091. if attachment_begin_index>-1 and last_sentence_index[0]<attachment_begin_index:
  2092. outline_list.append(Outline(doc_id,outline_index,'',last_sentence_index[0],attachment_begin_index-1,last_sentence_index[1],len(temp_sentences[attachment_begin_index-1])))
  2093. else:
  2094. outline_list.append(Outline(doc_id,outline_index,'',last_sentence_index[0],len(sentences)-1,last_sentence_index[1],len(temp_sentences[-1])))
  2095. sentences = temp_sentences
  2096. #解析outline的outline_text内容
  2097. for _outline in outline_list:
  2098. if _outline.sentence_begin_index==_outline.sentence_end_index:
  2099. _text = sentences[_outline.sentence_begin_index][_outline.wordOffset_begin:_outline.wordOffset_end]
  2100. else:
  2101. _text = ""
  2102. for idx in range(_outline.sentence_begin_index,_outline.sentence_end_index+1):
  2103. if idx==_outline.sentence_begin_index:
  2104. _text += sentences[idx][_outline.wordOffset_begin:]
  2105. elif idx==_outline.sentence_end_index:
  2106. _text += sentences[idx][:_outline.wordOffset_end]
  2107. else:
  2108. _text += sentences[idx]
  2109. _outline.outline_text = _text
  2110. _outline_summary = re.split("[::,]",_text,1)[0]
  2111. if len(_outline_summary)<20:
  2112. _outline.outline_summary = _outline_summary
  2113. # print(_outline.outline_index,_outline.outline_text)
  2114. article.content = "".join(sentences)
  2115. # sentences.append(article_processed[_begin:])
  2116. lemmas = []
  2117. doc_offsets = []
  2118. dep_types = []
  2119. dep_tokens = []
  2120. time1 = time.time()
  2121. '''
  2122. tokens_all = fool.cut(sentences)
  2123. #pos_all = fool.LEXICAL_ANALYSER.pos(tokens_all)
  2124. #ner_tag_all = fool.LEXICAL_ANALYSER.ner_labels(sentences,tokens_all)
  2125. ner_entitys_all = fool.ner(sentences)
  2126. '''
  2127. #限流执行
  2128. key_nerToken = "nerToken"
  2129. start_time = time.time()
  2130. # tokens_all = getTokens(sentences,useselffool=useselffool)
  2131. tokens_all = getTokens([re.sub("##attachment_begin##|##attachment_end##","",_sen) for _sen in sentences],useselffool=useselffool)
  2132. if key_nerToken not in cost_time:
  2133. cost_time[key_nerToken] = 0
  2134. cost_time[key_nerToken] += round(time.time()-start_time,2)
  2135. in_attachment = False
  2136. for sentence_index in range(len(sentences)):
  2137. sentence_text = sentences[sentence_index]
  2138. if re.search("##attachment_begin##",sentence_text):
  2139. in_attachment = True
  2140. sentence_text = re.sub("##attachment_begin##","",sentence_text)
  2141. if re.search("##attachment_end##",sentence_text):
  2142. in_attachment = False
  2143. sentence_text = re.sub("##attachment_end##", "", sentence_text)
  2144. if sentence_index >= attachment_begin_index and attachment_begin_index!=-1:
  2145. in_attachment = True
  2146. tokens = tokens_all[sentence_index]
  2147. #pos_tag = pos_all[sentence_index]
  2148. pos_tag = ""
  2149. ner_entitys = ""
  2150. 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,in_attachment=in_attachment))
  2151. if len(list_sentences_temp)==0:
  2152. list_sentences_temp.append(Sentences(doc_id=doc_id,sentence_index=0,sentence_text="sentence_text",tokens=[],pos_tags=[],ner_tags=""))
  2153. list_sentences.append(list_sentences_temp)
  2154. list_outlines.append(outline_list)
  2155. article.content = re.sub("##attachment_begin##|##attachment_end##", "", article.content)
  2156. return list_sentences,list_outlines
  2157. def get_preprocessed_entitys(list_sentences,useselffool=True,cost_time=dict()):
  2158. '''
  2159. :param list_sentences:分局情况
  2160. :param cost_time:
  2161. :return: list_entitys
  2162. '''
  2163. list_entitys = []
  2164. for list_sentence in list_sentences:
  2165. sentences = []
  2166. list_entitys_temp = []
  2167. for _sentence in list_sentence:
  2168. sentences.append(_sentence.sentence_text)
  2169. lemmas = []
  2170. doc_offsets = []
  2171. dep_types = []
  2172. dep_tokens = []
  2173. time1 = time.time()
  2174. '''
  2175. tokens_all = fool.cut(sentences)
  2176. #pos_all = fool.LEXICAL_ANALYSER.pos(tokens_all)
  2177. #ner_tag_all = fool.LEXICAL_ANALYSER.ner_labels(sentences,tokens_all)
  2178. ner_entitys_all = fool.ner(sentences)
  2179. '''
  2180. #限流执行
  2181. key_nerToken = "nerToken"
  2182. start_time = time.time()
  2183. found_yeji = 0 # 2021/8/6 增加判断是否正文包含评标结果 及类似业绩判断用于过滤后面的金额
  2184. # found_pingbiao = False
  2185. ner_entitys_all = getNers(sentences,useselffool=useselffool)
  2186. if key_nerToken not in cost_time:
  2187. cost_time[key_nerToken] = 0
  2188. cost_time[key_nerToken] += round(time.time()-start_time,2)
  2189. company_dict = set()
  2190. company_index = dict((i,set()) for i in range(len(list_sentence)))
  2191. for sentence_index in range(len(list_sentence)):
  2192. list_sentence_entitys = []
  2193. sentence_text = list_sentence[sentence_index].sentence_text
  2194. tokens = list_sentence[sentence_index].tokens
  2195. doc_id = list_sentence[sentence_index].doc_id
  2196. in_attachment = list_sentence[sentence_index].in_attachment
  2197. list_tokenbegin = []
  2198. begin = 0
  2199. for i in range(0,len(tokens)):
  2200. list_tokenbegin.append(begin)
  2201. begin += len(str(tokens[i]))
  2202. list_tokenbegin.append(begin+1)
  2203. #pos_tag = pos_all[sentence_index]
  2204. pos_tag = ""
  2205. ner_entitys = ner_entitys_all[sentence_index]
  2206. '''正则识别角色实体 经营部|经销部|电脑部|服务部|复印部|印刷部|彩印部|装饰部|修理部|汽修部|修理店|零售店|设计店|服务店|家具店|专卖店|分店|文具行|商行|印刷厂|修理厂|维修中心|修配中心|养护中心|服务中心|会馆|文化馆|超市|门市|商场|家具城|印刷社|经销处'''
  2207. for it in re.finditer(
  2208. '(?P<text_key_word>(((单一来源|中标|中选|中价|成交)(供应商|供货商|服务商|候选人|单位|人))|(供应商|供货商|服务商|候选人))(名称)?[为::]+)(?P<text>([()\w]{5,20})(厂|中心|超市|门市|商场|工作室|文印室|城|部|店|站|馆|行|社|处))[,。]',
  2209. sentence_text):
  2210. for k, v in it.groupdict().items():
  2211. if k == 'text_key_word':
  2212. keyword = v
  2213. if k == 'text':
  2214. entity = v
  2215. b = it.start() + len(keyword)
  2216. e = it.end() - 1
  2217. if (b, e, 'location', entity) in ner_entitys:
  2218. ner_entitys.remove((b, e, 'location', entity))
  2219. ner_entitys.append((b, e, 'company', entity))
  2220. elif (b, e, 'org', entity) not in ner_entitys and (b, e, 'company', entity) not in ner_entitys:
  2221. ner_entitys.append((b, e, 'company', entity))
  2222. for it in re.finditer(
  2223. '(?P<text_key_word>((建设|招租|招标|采购)(单位|人)|业主)(名称)?[为::]+)(?P<text>\w{2,4}[省市县区镇]([()\w]{2,20})(管理处|办公室|委员会|村委会|纪念馆|监狱|管教所|修养所|社区|农场|林场|羊场|猪场|石场|村|幼儿园))[,。]',
  2224. sentence_text):
  2225. for k, v in it.groupdict().items():
  2226. if k == 'text_key_word':
  2227. keyword = v
  2228. if k == 'text':
  2229. entity = v
  2230. b = it.start() + len(keyword)
  2231. e = it.end() - 1
  2232. if (b, e, 'location', entity) in ner_entitys:
  2233. ner_entitys.remove((b, e, 'location', entity))
  2234. ner_entitys.append((b, e, 'org', entity))
  2235. if (b, e, 'org', entity) not in ner_entitys and (b, e, 'company', entity) not in ner_entitys:
  2236. ner_entitys.append((b, e, 'org', entity))
  2237. for ner_entity in ner_entitys:
  2238. if ner_entity[2] in ['company','org']:
  2239. company_dict.add((ner_entity[2],ner_entity[3]))
  2240. company_index[sentence_index].add((ner_entity[0],ner_entity[1]))
  2241. #识别package
  2242. #识别实体
  2243. for ner_entity in ner_entitys:
  2244. begin_index_temp = ner_entity[0]
  2245. end_index_temp = ner_entity[1]
  2246. entity_type = ner_entity[2]
  2247. entity_text = ner_entity[3]
  2248. if entity_type in ["org","company"] and not isLegalEnterprise(entity_text):
  2249. continue
  2250. # 实体长度限制
  2251. if entity_type in ["org","company"] and len(entity_text)>30:
  2252. continue
  2253. if entity_type == "person" and len(entity_text) > 20:
  2254. continue
  2255. elif entity_type=="person" and len(entity_text)>10 and len(re.findall("[\u4e00-\u9fa5]",entity_text))<len(entity_text)/2:
  2256. continue
  2257. # 组织机构实体名称补充
  2258. if entity_type in ["org", "company"]:
  2259. fix_name = re.search("(有限)([责贵]?任?)(公?司?)",entity_text)
  2260. if fix_name:
  2261. if len(fix_name.group(2))>0:
  2262. entity_text = entity_text.replace(fix_name.group(), "有限责任公司")
  2263. elif len(fix_name.group(3))>0:
  2264. entity_text = entity_text.replace(fix_name.group(), "有限公司")
  2265. elif re.search("有限$", entity_text):
  2266. entity_text = re.sub("有限$","有限公司",entity_text)
  2267. for j in range(len(list_tokenbegin)):
  2268. if list_tokenbegin[j]==begin_index_temp:
  2269. begin_index = j
  2270. break
  2271. elif list_tokenbegin[j]>begin_index_temp:
  2272. begin_index = j-1
  2273. break
  2274. begin_index_temp += len(str(entity_text))
  2275. for j in range(begin_index,len(list_tokenbegin)):
  2276. if list_tokenbegin[j]>=begin_index_temp:
  2277. end_index = j-1
  2278. break
  2279. entity_id = "%s_%d_%d_%d"%(doc_id,sentence_index,begin_index,end_index)
  2280. #去掉标点符号
  2281. entity_text = re.sub("[,,。:!&@$\*]","",entity_text)
  2282. entity_text = entity_text.replace("(","(").replace(")",")") if isinstance(entity_text,str) else entity_text
  2283. 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],in_attachment=in_attachment))
  2284. # 标记文章末尾的"发布人”、“发布时间”实体
  2285. if sentence_index==len(list_sentence)-1:
  2286. if len(list_sentence_entitys[-2:])>2:
  2287. second2last = list_sentence_entitys[-2]
  2288. last = list_sentence_entitys[-1]
  2289. if (second2last.entity_type in ["company",'org'] and last.entity_type=="time") or (
  2290. second2last.entity_type=="time" and last.entity_type in ["company",'org']):
  2291. if last.wordOffset_begin - second2last.wordOffset_end < 6 and len(sentence_text) - last.wordOffset_end<6:
  2292. last.is_tail = True
  2293. second2last.is_tail = True
  2294. #使用正则识别金额
  2295. entity_type = "money"
  2296. #money_patten_str = "(([1-9][\d,,]*(?:\.\d+)?[百千万亿]?[\(\)()元整]+)|([零壹贰叁肆伍陆柒捌玖拾佰仟萬億十百千万亿元角分]{3,})|(?:[¥¥]+,?|报价|标价)[(\(]?([万])?元?[)\)]?[::]?.{,7}?([1-9][\d,,]*(?:\.\d+)?(?:,?)[百千万亿]?)|([1-9][\d,,]*(?:\.\d+)?(?:,?)[百千万亿]?)[\((]?([万元]{1,2}))*"
  2297. # list_money_pattern = {"cn":"(()()(?P<money_cn>[零壹贰叁肆伍陆柒捌玖拾佰仟萬億圆十百千万亿元角分]{3,})())",
  2298. # "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*[)\)]?))",
  2299. # "front_m":"((?P<text_front_m>(?:[(\(]?\s*(?P<unit_front_m_before>[万元]+)\s*[)\)])\s*[,,::]*(\s*[^壹贰叁肆伍陆柒捌玖拾佰仟萬億分万元]{,7}?))(?P<money_front_m>[0-9][\d,]*(?:\.\d+)?(?:,?)[百千万亿元]*)())",
  2300. # "behind_m":"(()()(?P<money_behind_m>[0-9][\d,,]*(?:\.\d+)?(?:,?)[百千万亿]*)[\((]?(?P<unit_behind_m>[万元]+(?P<filter_unit3>[台个只]*))[\))]?)"}
  2301. list_money_pattern = {"cn":"(()()(?P<money_cn>[零壹贰叁肆伍陆柒捌玖拾佰仟萬億圆十百千万亿元角分]{3,})())",
  2302. "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*[)\)]?))",
  2303. "front_m":"((?P<text_front_m>(?:[(\(]?\s*(?P<unit_front_m_before>[万亿]?[美日欧]?元)\s*[)\)])\s*[,,::]*(\s*[^壹贰叁肆伍陆柒捌玖拾佰仟萬億分万元]{,7}?))(?P<money_front_m>[0-9][\d,]*(?:\.\d+)?(?:,?)[百千]*)())",
  2304. "behind_m":"(()()(?P<money_behind_m>[0-9][\d,]*(?:\.\d+)?(?:,?)[百千]*)(人民币)?[\((]?(?P<unit_behind_m>[万亿]?[美日欧]?元(?P<filter_unit3>[台个只吨斤棵株页亩方条米]*))[\))]?)"}
  2305. # 2021/7/19 调整金额,单位提取正则,修复部分金额因为单位提取失败被过滤问题。
  2306. 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"]))
  2307. set_begin = set()
  2308. # for pattern_key in list_money_pattern.keys():
  2309. # for pattern_key in ["cn","key_word","behind_m","front_m"]:
  2310. # # pattern = re.compile(list_money_pattern[pattern_key])
  2311. # 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+)?(?:,?)[百千万亿元]*)())*")
  2312. # all_match = re.findall(pattern, sentence_text)
  2313. # index = 0
  2314. # for i in range(len(all_match)):
  2315. # if len(all_match[i][0])>0:
  2316. # print("===",all_match[i])
  2317. # #print(all_match[i][0])
  2318. # unit = ""
  2319. # entity_text = all_match[i][3]
  2320. # if pattern_key in ["key_word","front_m"]:
  2321. # unit = all_match[i][1]
  2322. # if pattern_key=="key_word":
  2323. # if all_match[i][1]=="" and all_match[i][4]!="":
  2324. # unit = all_match[i][4]
  2325. # else:
  2326. # unit = all_match[i][4]
  2327. # if entity_text.find("元")>=0:
  2328. # unit = ""
  2329. #
  2330. # index += len(all_match[i][0])-len(entity_text)-len(all_match[i][4])#-len(all_match[i][1])-len(all_match[i][2])#整个提出来的作为实体->数字部分作为整体,否则会丢失特征
  2331. # begin_index_temp = index
  2332. # for j in range(len(list_tokenbegin)):
  2333. # if list_tokenbegin[j]==index:
  2334. # begin_index = j
  2335. # break
  2336. # elif list_tokenbegin[j]>index:
  2337. # begin_index = j-1
  2338. # break
  2339. # index += len(str(entity_text))+len(all_match[i][4])#+len(all_match[i][2])+len(all_match[i][1])#整个提出来的作为实体
  2340. # end_index_temp = index
  2341. # #index += len(str(all_match[i][0]))
  2342. # for j in range(begin_index,len(list_tokenbegin)):
  2343. # if list_tokenbegin[j]>=index:
  2344. # end_index = j-1
  2345. # break
  2346. # entity_id = "%s_%d_%d_%d"%(doc_id,sentence_index,begin_index,end_index)
  2347. #
  2348. # entity_text = re.sub("[^0-9.零壹贰叁肆伍陆柒捌玖拾佰仟萬億十百千万亿元角分]","",entity_text)
  2349. # if len(unit)>0:
  2350. # entity_text = str(getUnifyMoney(entity_text)*getMultipleFactor(unit[0]))
  2351. # else:
  2352. # entity_text = str(getUnifyMoney(entity_text))
  2353. #
  2354. # _exists = False
  2355. # for item in list_sentence_entitys:
  2356. # if item.entity_id==entity_id and item.entity_type==entity_type:
  2357. # _exists = True
  2358. # if not _exists:
  2359. # if float(entity_text)>1:
  2360. # 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))
  2361. #
  2362. # else:
  2363. # index += 1
  2364. # if re.search('评标结果|候选人公示', sentence_text):
  2365. # found_pingbiao = True
  2366. if re.search('业绩', sentence_text):
  2367. found_yeji += 1
  2368. if found_yeji >= 2: # 过滤掉业绩后面的所有金额
  2369. all_match = []
  2370. else:
  2371. all_match = re.finditer(pattern_money, sentence_text)
  2372. index = 0
  2373. for _match in all_match:
  2374. if len(_match.group())>0:
  2375. # print("===",_match.group())
  2376. # # print(_match.groupdict())
  2377. notes = '' # 2021/7/20 新增备注金额大写或金额单位 if 金额大写 notes=大写 elif 单位 notes=单位
  2378. unit = ""
  2379. entity_text = ""
  2380. text_beforeMoney = ""
  2381. filter = ""
  2382. filter_unit = False
  2383. notSure = False
  2384. if re.search('业绩', sentence_text[:_match.span()[0]]): # 2021/7/21过滤掉业绩后面金额
  2385. # print('金额在业绩后面: ', _match.group(0))
  2386. found_yeji += 1
  2387. break
  2388. for k,v in _match.groupdict().items():
  2389. if v!="" and v is not None:
  2390. if k=='text_key_word':
  2391. notSure = True
  2392. if k.split("_")[0]=="money":
  2393. entity_text = v
  2394. if k.split("_")[0]=="unit":
  2395. if v=='万元' or unit=="": # 处理 预算金额(元):160万元 这种出现前后单位不一致情况
  2396. unit = v
  2397. if k.split("_")[0]=="text":
  2398. text_beforeMoney = v
  2399. if k.split("_")[0]=="filter":
  2400. filter = v
  2401. if re.search("filter_unit",k) is not None:
  2402. filter_unit = True
  2403. # print(_match.group())
  2404. # print(entity_text,unit,text_beforeMoney,filter,filter_unit)
  2405. if re.search('(^\d{2,},\d{4,}万?$)|(^\d{2,},\d{2}万?$)', entity_text.strip()): # 2021/7/19 修正OCR识别小数点为逗号
  2406. if re.search('[幢栋号楼层]', sentence_text[max(0, _match.span()[0]-2):_match.span()[0]]):
  2407. entity_text = re.sub('\d+,', '', entity_text)
  2408. else:
  2409. entity_text = entity_text.replace(',', '.')
  2410. # print(' 修正OCR识别小数点为逗号')
  2411. if entity_text.find("元")>=0:
  2412. unit = ""
  2413. if unit == "": #2021/7/21 有明显金额特征的补充单位,避免被过滤
  2414. if ('¥' in text_beforeMoney or '¥' in text_beforeMoney):
  2415. unit = '元'
  2416. # print('明显金额特征补充单位 元')
  2417. elif re.search('[单报标限]价|金额|价格|(监理|设计|勘察)(服务)?费[::为]+$', text_beforeMoney.strip()) and \
  2418. re.search('\d{5,}',entity_text) and re.search('^0|1[3|4|5|6|7|8|9]\d{9}',entity_text)==None:
  2419. unit = '元'
  2420. # print('明显金额特征补充单位 元')
  2421. elif re.search('(^\d{,3}(,?\d{3})+(\.\d{2,7},?)$)|(^\d{,3}(,\d{3})+,?$)',entity_text):
  2422. unit = '元'
  2423. # print('明显金额特征补充单位 元')
  2424. if unit.find("万") >= 0 and entity_text.find("万") >= 0: #2021/7/19修改为金额文本有万,不计算单位
  2425. # print('修正金额及单位都有万, 金额:',entity_text, '单位:',unit)
  2426. unit = "元"
  2427. if re.search('.*万元万元', entity_text): #2021/7/19 修正两个万元
  2428. # print(' 修正两个万元',entity_text)
  2429. entity_text = entity_text.replace('万元万元','万元')
  2430. else:
  2431. if filter_unit:
  2432. continue
  2433. if filter!="":
  2434. continue
  2435. index = _match.span()[0]+len(text_beforeMoney)
  2436. begin_index_temp = index
  2437. for j in range(len(list_tokenbegin)):
  2438. if list_tokenbegin[j]==index:
  2439. begin_index = j
  2440. break
  2441. elif list_tokenbegin[j]>index:
  2442. begin_index = j-1
  2443. break
  2444. index = _match.span()[1]
  2445. end_index_temp = index
  2446. #index += len(str(all_match[i][0]))
  2447. for j in range(begin_index,len(list_tokenbegin)):
  2448. if list_tokenbegin[j]>=index:
  2449. end_index = j-1
  2450. break
  2451. entity_id = "%s_%d_%d_%d"%(doc_id,sentence_index,begin_index,end_index)
  2452. entity_text = re.sub("[^0-9.零壹贰叁肆伍陆柒捌玖拾佰仟萬億圆十百千万亿元角分]","",entity_text)
  2453. # print('转换前金额:', entity_text, '单位:', unit, '备注:',notes, 'text_beforeMoney:',text_beforeMoney)
  2454. if re.search('总投资|投资总额|总预算|总概算|投资规模|批复概算', sentence_text[max(0, _match.span()[0] - 8):_match.span()[1]]): # 2021/8/5过滤掉总投资金额
  2455. # print('总投资金额: ', _match.group(0))
  2456. notes = '总投资'
  2457. elif re.search('投资|概算', sentence_text[max(0, _match.span()[0] - 8):_match.span()[1]]): # 2021/11/18 投资金额不作为招标金额
  2458. notes = '投资'
  2459. elif re.search('工程造价', sentence_text[max(0, _match.span()[0] - 8):_match.span()[1]]): # 2021/12/20 工程造价不作为招标金额
  2460. notes = '工程造价'
  2461. elif (re.search('保证金', sentence_text[max(0, _match.span()[0] - 5):_match.span()[1]])
  2462. or re.search('保证金的?(缴纳)?(金额|金\?|额|\?)?[\((]*(万?元|为?人民币|大写|调整|变更|已?修改|更改|更正)?[\))]*[::为]',
  2463. sentence_text[max(0, _match.span()[0] - 10):_match.span()[1]])
  2464. or re.search('保证金由[\d.,]+.{,3}(变更|修改|更改|更正|调整?)为',
  2465. sentence_text[max(0, _match.span()[0] - 15):_match.span()[1]])):
  2466. notes = '保证金'
  2467. # print('保证金信息:', sentence_text[max(0, _match.span()[0] - 15):_match.span()[1]])
  2468. elif re.search('成本(警戒|预警)(线|价|值)[^0-9元]{,10}',
  2469. sentence_text[max(0, _match.span()[0] - 10):_match.span()[0]]):
  2470. notes = '成本警戒线'
  2471. elif re.search('(监理|设计|勘察)(服务)?费(报价)?[约为:]', sentence_text[_match.span()[0]:_match.span()[1]]):
  2472. cost_re = re.search('(监理|设计|勘察)(服务)?费', sentence_text[_match.span()[0]:_match.span()[1]])
  2473. notes = cost_re.group(1)
  2474. elif re.search('单价|总金额', sentence_text[_match.span()[0]:_match.span()[1]]):
  2475. notes = '单价'
  2476. elif re.search('[零壹贰叁肆伍陆柒捌玖拾佰仟萬億圆]', entity_text) != None:
  2477. notes = '大写'
  2478. if entity_text[0] == "拾": # 2021/12/16 修正大写金额省略了数字转换错误问题
  2479. entity_text = "壹"+entity_text
  2480. # print("补充备注:notes = 大写")
  2481. if len(unit)>0:
  2482. if unit.find('万')>=0 and len(entity_text.split('.')[0])>=8: # 2021/7/19 修正万元金额过大的情况
  2483. # print('修正单位万元金额过大的情况 金额:', entity_text, '单位:', unit)
  2484. entity_text = str(getUnifyMoney(entity_text) * getMultipleFactor(re.sub("[美日欧]","",unit)[0])/10000)
  2485. unit = '元' # 修正金额后单位 重置为元
  2486. else:
  2487. # print('str(getUnifyMoney(entity_text)*getMultipleFactor(unit[0])):')
  2488. entity_text = str(getUnifyMoney(entity_text)*getMultipleFactor(re.sub("[美日欧]","",unit)[0]))
  2489. else:
  2490. if entity_text.find('万')>=0 and entity_text.split('.')[0].isdigit() and len(entity_text.split('.')[0])>=8:
  2491. entity_text = str(getUnifyMoney(entity_text)/10000)
  2492. # print('修正金额字段含万 过大的情况')
  2493. else:
  2494. entity_text = str(getUnifyMoney(entity_text))
  2495. if float(entity_text)>100000000000 or float(entity_text)<100: # float(entity_text)<100 or 2022/3/4 取消最小金额限制
  2496. # print('过滤掉金额:float(entity_text)<100 or float(entity_text)>100000000000', entity_text, unit)
  2497. continue
  2498. if notSure and unit=="" and float(entity_text)>100*10000:
  2499. # print('过滤掉金额 notSure and unit=="" and float(entity_text)>100*10000:', entity_text, unit)
  2500. continue
  2501. if re.search("美元",_match.group()):
  2502. Dollar2RMB = 7
  2503. entity_text = str(float(entity_text)*Dollar2RMB)
  2504. elif re.search("日元",_match.group()):
  2505. JPyen2RMB = 0.05
  2506. entity_text = str(float(entity_text)*JPyen2RMB)
  2507. elif re.search("欧元",_match.group()):
  2508. Euro2RMB = 6.9
  2509. entity_text = str(float(entity_text)*Euro2RMB)
  2510. _exists = False
  2511. for item in list_sentence_entitys:
  2512. if item.entity_id==entity_id and item.entity_type==entity_type:
  2513. _exists = True
  2514. if (begin_index >=item.begin_index and begin_index<=item.end_index) or (end_index>=item.begin_index and end_index<=item.end_index):
  2515. _exists = True
  2516. if not _exists:
  2517. if float(entity_text)>1:
  2518. 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,in_attachment=in_attachment))
  2519. list_sentence_entitys[-1].notes = notes # 2021/7/20 新增金额备注
  2520. list_sentence_entitys[-1].money_unit = unit # 2021/7/20 新增金额备注
  2521. # print('预处理中的 金额:%s, 单位:%s'%(entity_text,unit))
  2522. # print(entity_text,unit,notes)
  2523. else:
  2524. index += 1
  2525. # "联系人"正则补充提取 2021/11/15 新增
  2526. list_person_text = [entity.entity_text for entity in list_sentence_entitys if entity.entity_type=='person']
  2527. error_text = ['交易','机构','教育','项目','公司','中标','开标','截标','监督','政府','国家','中国','技术','投标','传真','网址','电子邮',
  2528. '联系','联系电','联系地','采购代','邮政编','邮政','电话','手机','手机号','联系人','地址','地点','邮箱','邮编','联系方','招标','招标人','代理',
  2529. '代理人','采购','附件','注意','登录','报名','踏勘',"测试",'交货']
  2530. list_person_text = set(list_person_text + error_text)
  2531. re_person = re.compile("联系人[::]([\u4e00-\u9fa5]工)|"
  2532. "联系人[::]([\u4e00-\u9fa5]{2,3})(?=,?联系)|"
  2533. "联系人[::]([\u4e00-\u9fa5]{2,3})(?=[,。;、])"
  2534. )
  2535. list_person = []
  2536. if not in_attachment:
  2537. for match_result in re_person.finditer(sentence_text):
  2538. match_text = match_result.group()
  2539. entity_text = match_text[4:]
  2540. wordOffset_begin = match_result.start() + 4
  2541. wordOffset_end = match_result.end()
  2542. # print(text[wordOffset_begin:wordOffset_end])
  2543. # 排除一些不为人名的实体
  2544. if re.search("^[\u4e00-\u9fa5]{7,}([,。]|$)",sentence_text[wordOffset_begin:wordOffset_begin+20]):
  2545. continue
  2546. if entity_text not in list_person_text and entity_text[:2] not in list_person_text:
  2547. _person = dict()
  2548. _person['body'] = entity_text
  2549. _person['begin_index'] = wordOffset_begin
  2550. _person['end_index'] = wordOffset_end
  2551. list_person.append(_person)
  2552. entity_type = "person"
  2553. for person in list_person:
  2554. begin_index_temp = person['begin_index']
  2555. for j in range(len(list_tokenbegin)):
  2556. if list_tokenbegin[j] == begin_index_temp:
  2557. begin_index = j
  2558. break
  2559. elif list_tokenbegin[j] > begin_index_temp:
  2560. begin_index = j - 1
  2561. break
  2562. index = person['end_index']
  2563. end_index_temp = index
  2564. for j in range(begin_index, len(list_tokenbegin)):
  2565. if list_tokenbegin[j] >= index:
  2566. end_index = j - 1
  2567. break
  2568. entity_id = "%s_%d_%d_%d" % (doc_id, sentence_index, begin_index, end_index)
  2569. entity_text = person['body']
  2570. list_sentence_entitys.append(
  2571. Entity(doc_id, entity_id, entity_text, entity_type, sentence_index, begin_index, end_index,
  2572. begin_index_temp, end_index_temp,in_attachment=in_attachment))
  2573. # 资金来源提取 2020/12/30 新增
  2574. list_moneySource = extract_moneySource(sentence_text)
  2575. entity_type = "moneysource"
  2576. for moneySource in list_moneySource:
  2577. entity_text = moneySource['body']
  2578. if len(entity_text)>50:
  2579. continue
  2580. begin_index_temp = moneySource['begin_index']
  2581. for j in range(len(list_tokenbegin)):
  2582. if list_tokenbegin[j] == begin_index_temp:
  2583. begin_index = j
  2584. break
  2585. elif list_tokenbegin[j] > begin_index_temp:
  2586. begin_index = j - 1
  2587. break
  2588. index = moneySource['end_index']
  2589. end_index_temp = index
  2590. for j in range(begin_index, len(list_tokenbegin)):
  2591. if list_tokenbegin[j] >= index:
  2592. end_index = j - 1
  2593. break
  2594. entity_id = "%s_%d_%d_%d" % (doc_id, sentence_index, begin_index, end_index)
  2595. list_sentence_entitys.append(
  2596. Entity(doc_id, entity_id, entity_text, entity_type, sentence_index, begin_index, end_index,
  2597. begin_index_temp, end_index_temp,in_attachment=in_attachment))
  2598. # 电子邮箱提取 2021/11/04 新增
  2599. list_email = extract_email(sentence_text)
  2600. entity_type = "email" # 电子邮箱
  2601. for email in list_email:
  2602. begin_index_temp = email['begin_index']
  2603. for j in range(len(list_tokenbegin)):
  2604. if list_tokenbegin[j] == begin_index_temp:
  2605. begin_index = j
  2606. break
  2607. elif list_tokenbegin[j] > begin_index_temp:
  2608. begin_index = j - 1
  2609. break
  2610. index = email['end_index']
  2611. end_index_temp = index
  2612. for j in range(begin_index, len(list_tokenbegin)):
  2613. if list_tokenbegin[j] >= index:
  2614. end_index = j - 1
  2615. break
  2616. entity_id = "%s_%d_%d_%d" % (doc_id, sentence_index, begin_index, end_index)
  2617. entity_text = email['body']
  2618. list_sentence_entitys.append(
  2619. Entity(doc_id, entity_id, entity_text, entity_type, sentence_index, begin_index, end_index,
  2620. begin_index_temp, end_index_temp,in_attachment=in_attachment))
  2621. # 服务期限提取 2020/12/30 新增
  2622. list_servicetime = extract_servicetime(sentence_text)
  2623. entity_type = "serviceTime"
  2624. for servicetime in list_servicetime:
  2625. entity_text = servicetime['body']
  2626. begin_index_temp = servicetime['begin_index']
  2627. for j in range(len(list_tokenbegin)):
  2628. if list_tokenbegin[j] == begin_index_temp:
  2629. begin_index = j
  2630. break
  2631. elif list_tokenbegin[j] > begin_index_temp:
  2632. begin_index = j - 1
  2633. break
  2634. index = servicetime['end_index']
  2635. end_index_temp = index
  2636. for j in range(begin_index, len(list_tokenbegin)):
  2637. if list_tokenbegin[j] >= index:
  2638. end_index = j - 1
  2639. break
  2640. entity_id = "%s_%d_%d_%d" % (doc_id, sentence_index, begin_index, end_index)
  2641. list_sentence_entitys.append(
  2642. Entity(doc_id, entity_id, entity_text, entity_type, sentence_index, begin_index, end_index,
  2643. begin_index_temp, end_index_temp,in_attachment=in_attachment, prob=servicetime["prob"]))
  2644. # 招标方式提取 2020/12/30 新增
  2645. # list_bidway = extract_bidway(sentence_text, )
  2646. # entity_type = "bidway"
  2647. # for bidway in list_bidway:
  2648. # begin_index_temp = bidway['begin_index']
  2649. # end_index_temp = bidway['end_index']
  2650. # begin_index = changeIndexFromWordToWords(tokens, begin_index_temp)
  2651. # end_index = changeIndexFromWordToWords(tokens, end_index_temp)
  2652. # if begin_index is None or end_index is None:
  2653. # continue
  2654. # print(begin_index_temp,end_index_temp,begin_index,end_index)
  2655. # entity_id = "%s_%d_%d_%d" % (doc_id, sentence_index, begin_index, end_index)
  2656. # entity_text = bidway['body']
  2657. # list_sentence_entitys.append(
  2658. # Entity(doc_id, entity_id, entity_text, entity_type, sentence_index, begin_index, end_index,
  2659. # begin_index_temp, end_index_temp))
  2660. # 2021/12/29 新增比率提取
  2661. list_ratio = extract_ratio(sentence_text)
  2662. entity_type = "ratio"
  2663. for ratio in list_ratio:
  2664. # print("ratio", ratio)
  2665. begin_index_temp = ratio['begin_index']
  2666. for j in range(len(list_tokenbegin)):
  2667. if list_tokenbegin[j] == begin_index_temp:
  2668. begin_index = j
  2669. break
  2670. elif list_tokenbegin[j] > begin_index_temp:
  2671. begin_index = j - 1
  2672. break
  2673. index = ratio['end_index']
  2674. end_index_temp = index
  2675. for j in range(begin_index, len(list_tokenbegin)):
  2676. if list_tokenbegin[j] >= index:
  2677. end_index = j - 1
  2678. break
  2679. entity_id = "%s_%d_%d_%d" % (doc_id, sentence_index, begin_index, end_index)
  2680. entity_text = ratio['body']
  2681. list_sentence_entitys.append(
  2682. Entity(doc_id, entity_id, entity_text, entity_type, sentence_index, begin_index, end_index,
  2683. begin_index_temp, end_index_temp,in_attachment=in_attachment))
  2684. list_sentence_entitys.sort(key=lambda x:x.begin_index)
  2685. list_entitys_temp = list_entitys_temp+list_sentence_entitys
  2686. # 补充ner模型未识别全的company/org实体
  2687. for sentence_index in range(len(list_sentence)):
  2688. sentence_text = list_sentence[sentence_index].sentence_text
  2689. tokens = list_sentence[sentence_index].tokens
  2690. doc_id = list_sentence[sentence_index].doc_id
  2691. in_attachment = list_sentence[sentence_index].in_attachment
  2692. list_tokenbegin = []
  2693. begin = 0
  2694. for i in range(0, len(tokens)):
  2695. list_tokenbegin.append(begin)
  2696. begin += len(str(tokens[i]))
  2697. list_tokenbegin.append(begin + 1)
  2698. add_sentence_entitys = []
  2699. company_dict = sorted(list(company_dict),key=lambda x:len(x[1]),reverse=True)
  2700. for company_type,company_text in company_dict:
  2701. begin_index_list = findAllIndex(company_text,sentence_text)
  2702. for begin_index in begin_index_list:
  2703. is_continue = False
  2704. for t_begin,t_end in list(company_index[sentence_index]):
  2705. if begin_index>=t_begin and begin_index+len(company_text)<=t_end:
  2706. is_continue = True
  2707. break
  2708. if not is_continue:
  2709. add_sentence_entitys.append((begin_index,begin_index+len(company_text),company_type,company_text))
  2710. company_index[sentence_index].add((begin_index,begin_index+len(company_text)))
  2711. else:
  2712. continue
  2713. for ner_entity in add_sentence_entitys:
  2714. begin_index_temp = ner_entity[0]
  2715. end_index_temp = ner_entity[1]
  2716. entity_type = ner_entity[2]
  2717. entity_text = ner_entity[3]
  2718. if entity_type in ["org","company"] and not isLegalEnterprise(entity_text):
  2719. continue
  2720. for j in range(len(list_tokenbegin)):
  2721. if list_tokenbegin[j]==begin_index_temp:
  2722. begin_index = j
  2723. break
  2724. elif list_tokenbegin[j]>begin_index_temp:
  2725. begin_index = j-1
  2726. break
  2727. begin_index_temp += len(str(entity_text))
  2728. for j in range(begin_index,len(list_tokenbegin)):
  2729. if list_tokenbegin[j]>=begin_index_temp:
  2730. end_index = j-1
  2731. break
  2732. entity_id = "%s_%d_%d_%d"%(doc_id,sentence_index,begin_index,end_index)
  2733. #去掉标点符号
  2734. entity_text = re.sub("[,,。:!&@$\*]","",entity_text)
  2735. entity_text = entity_text.replace("(","(").replace(")",")") if isinstance(entity_text,str) else entity_text
  2736. list_entitys_temp.append(Entity(doc_id,entity_id,entity_text,entity_type,sentence_index,begin_index,end_index,ner_entity[0],ner_entity[1],in_attachment=in_attachment))
  2737. list_entitys_temp.sort(key=lambda x:(x.sentence_index,x.begin_index))
  2738. list_entitys.append(list_entitys_temp)
  2739. return list_entitys
  2740. def union_result(codeName,prem):
  2741. '''
  2742. @summary:模型的结果拼成字典
  2743. @param:
  2744. codeName:编号名称模型的结果字典
  2745. prem:拿到属性的角色的字典
  2746. @return:拼接起来的字典
  2747. '''
  2748. result = []
  2749. assert len(codeName)==len(prem)
  2750. for item_code,item_prem in zip(codeName,prem):
  2751. result.append(dict(item_code,**item_prem))
  2752. return result
  2753. def persistenceData(data):
  2754. '''
  2755. @summary:将中间结果保存到数据库-线上生产的时候不需要执行
  2756. '''
  2757. import psycopg2
  2758. conn = psycopg2.connect(dbname="BiddingKG",user="postgres",password="postgres",host="192.168.2.101")
  2759. cursor = conn.cursor()
  2760. for item_index in range(len(data)):
  2761. item = data[item_index]
  2762. doc_id = item[0]
  2763. dic = item[1]
  2764. code = dic['code']
  2765. name = dic['name']
  2766. prem = dic['prem']
  2767. if len(code)==0:
  2768. code_insert = ""
  2769. else:
  2770. code_insert = ";".join(code)
  2771. prem_insert = ""
  2772. for item in prem:
  2773. for x in item:
  2774. if isinstance(x, list):
  2775. if len(x)>0:
  2776. for x1 in x:
  2777. prem_insert+="/".join(x1)+","
  2778. prem_insert+="$"
  2779. else:
  2780. prem_insert+=str(x)+"$"
  2781. prem_insert+=";"
  2782. sql = " insert into predict_validation(doc_id,code,name,prem) values('"+doc_id+"','"+code_insert+"','"+name+"','"+prem_insert+"')"
  2783. cursor.execute(sql)
  2784. conn.commit()
  2785. conn.close()
  2786. def persistenceData1(list_entitys,list_sentences):
  2787. '''
  2788. @summary:将中间结果保存到数据库-线上生产的时候不需要执行
  2789. '''
  2790. import psycopg2
  2791. conn = psycopg2.connect(dbname="BiddingKG",user="postgres",password="postgres",host="192.168.2.101")
  2792. cursor = conn.cursor()
  2793. for list_entity in list_entitys:
  2794. for entity in list_entity:
  2795. if entity.values is not None:
  2796. 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)+")"
  2797. else:
  2798. 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)+")"
  2799. cursor.execute(sql)
  2800. for list_sentence in list_sentences:
  2801. for sentence in list_sentence:
  2802. str_tokens = "["
  2803. for item in sentence.tokens:
  2804. str_tokens += "'"
  2805. if item=="'":
  2806. str_tokens += "''"
  2807. else:
  2808. str_tokens += item
  2809. str_tokens += "',"
  2810. str_tokens = str_tokens[:-1]+"]"
  2811. sql = " insert into predict_sentences(doc_id,sentence_index,tokens) values('"+sentence.doc_id+"',"+str(sentence.sentence_index)+",array"+str_tokens+")"
  2812. cursor.execute(sql)
  2813. conn.commit()
  2814. conn.close()
  2815. def _handle(item,result_queue):
  2816. dochtml = item["dochtml"]
  2817. docid = item["docid"]
  2818. list_innerTable = tableToText(BeautifulSoup(dochtml,"lxml"))
  2819. flag = False
  2820. if list_innerTable:
  2821. flag = True
  2822. for table in list_innerTable:
  2823. result_queue.put({"docid":docid,"json_table":json.dumps(table,ensure_ascii=False)})
  2824. def getPredictTable():
  2825. filename = "D:\Workspace2016\DataExport\data\websouce_doc.csv"
  2826. import pandas as pd
  2827. import json
  2828. from BiddingKG.dl.common.MultiHandler import MultiHandler,Queue
  2829. df = pd.read_csv(filename)
  2830. df_data = {"json_table":[],"docid":[]}
  2831. _count = 0
  2832. _sum = len(df["docid"])
  2833. task_queue = Queue()
  2834. result_queue = Queue()
  2835. _index = 0
  2836. for dochtml,docid in zip(df["dochtmlcon"],df["docid"]):
  2837. task_queue.put({"docid":docid,"dochtml":dochtml,"json_table":None})
  2838. _index += 1
  2839. mh = MultiHandler(task_queue=task_queue,task_handler=_handle,result_queue=result_queue,process_count=5,thread_count=1)
  2840. mh.run()
  2841. while True:
  2842. try:
  2843. item = result_queue.get(block=True,timeout=1)
  2844. df_data["docid"].append(item["docid"])
  2845. df_data["json_table"].append(item["json_table"])
  2846. except Exception as e:
  2847. print(e)
  2848. break
  2849. df_1 = pd.DataFrame(df_data)
  2850. df_1.to_csv("../form/websource_67000_table.csv",columns=["docid","json_table"])
  2851. if __name__=="__main__":
  2852. '''
  2853. import glob
  2854. for file in glob.glob("C:\\Users\\User\\Desktop\\test\\*.html"):
  2855. file_txt = str(file).replace("html","txt")
  2856. with codecs.open(file_txt,"a+",encoding="utf8") as f:
  2857. f.write("\n================\n")
  2858. content = codecs.open(file,"r",encoding="utf8").read()
  2859. f.write(segment(tableToText(BeautifulSoup(content,"lxml"))))
  2860. '''
  2861. # content = codecs.open("C:\\Users\\User\\Desktop\\2.html","r",encoding="utf8").read()
  2862. # print(segment(tableToText(BeautifulSoup(content,"lxml"))))
  2863. # getPredictTable()
  2864. with open('D:/138786703.html', 'r', encoding='utf-8') as f:
  2865. sourceContent = f.read()
  2866. # article_processed = segment(tableToText(BeautifulSoup(sourceContent, "lxml")))
  2867. # print(article_processed)
  2868. list_articles, list_sentences, list_entitys, _cost_time = get_preprocessed([['doc_id', sourceContent, "", "", '', '2021-02-01']], useselffool=True)
  2869. for entity in list_entitys[0]:
  2870. print(entity.entity_type, entity.entity_text)