Preprocessing.py 220 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292
  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_torch 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, TableTag2List
  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, docid=None, return_kv=False):
  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. if return_kv:
  109. tr_line.append([re.sub('\xa0','',tr.get_text()),0])
  110. else:
  111. tr_line.append([re.sub('\xa0','',segment(tr,final=False)),0]) # 2021/12/21 修复部分表格没有td 造成数据丢失
  112. for td in tds:
  113. if return_kv:
  114. tr_line.append([re.sub('\xa0','',td.get_text()),0])
  115. else:
  116. tr_line.append([re.sub('\xa0','',segment(td,final=False)),0])
  117. #tr_line.append([td.get_text(),0])
  118. inner_table.append(tr_line)
  119. return inner_table
  120. #处理表格不对齐的问题
  121. def fixTable(inner_table,fix_value="~~"):
  122. maxWidth = 0
  123. for item in inner_table:
  124. if len(item)>maxWidth:
  125. maxWidth = len(item)
  126. if maxWidth > 100:
  127. # log('表格列数大于100,表格异常不做处理。')
  128. return []
  129. for i in range(len(inner_table)):
  130. if len(inner_table[i])<maxWidth:
  131. for j in range(maxWidth-len(inner_table[i])):
  132. inner_table[i].append([fix_value,0])
  133. return inner_table
  134. def removePadding(inner_table,pad_row = "@@",pad_col = "##"):
  135. height = len(inner_table)
  136. width = len(inner_table[0])
  137. for i in range(height):
  138. point = ""
  139. for j in range(width):
  140. if inner_table[i][j][0]==point and point!="":
  141. inner_table[i][j][0] = pad_row
  142. else:
  143. if inner_table[i][j][0] not in [pad_row,pad_col]:
  144. point = inner_table[i][j][0]
  145. for j in range(width):
  146. point = ""
  147. for i in range(height):
  148. if inner_table[i][j][0]==point and point!="":
  149. inner_table[i][j][0] = pad_col
  150. else:
  151. if inner_table[i][j][0] not in [pad_row,pad_col]:
  152. point = inner_table[i][j][0]
  153. def addPadding(inner_table,pad_row = "@@",pad_col = "##"):
  154. height = len(inner_table)
  155. width = len(inner_table[0])
  156. for i in range(height):
  157. for j in range(width):
  158. if inner_table[i][j][0]==pad_row:
  159. inner_table[i][j][0] = inner_table[i][j-1][0]
  160. inner_table[i][j][1] = inner_table[i][j-1][1]
  161. if inner_table[i][j][0]==pad_col:
  162. inner_table[i][j][0] = inner_table[i-1][j][0]
  163. inner_table[i][j][1] = inner_table[i-1][j][1]
  164. def repairTable(inner_table, dye_set=set(), key_set=set(), fix_value="~~"):
  165. """
  166. @summary: 修复表头识别,将明显错误的进行修正
  167. """
  168. def repairNeeded(line):
  169. first_1 = -1
  170. last_1 = -1
  171. first_0 = -1
  172. last_0 = -1
  173. count_1 = 0
  174. count_0 = 0
  175. for i in range(len(line)):
  176. if line[i][0] == fix_value:
  177. continue
  178. if line[i][1]==1:
  179. if first_1==-1:
  180. first_1 = i
  181. last_1 = i
  182. count_1 += 1
  183. if line[i][1]==0:
  184. if first_0 == -1:
  185. first_0 = i
  186. last_0 = i
  187. count_0 += 1
  188. if first_1 ==-1 or last_0 == -1:
  189. return False
  190. # 异常情况:第一个不是表头;最后一个是表头;表头个数远大于属性值个数
  191. if first_1-0 > 0 or last_0-len(line)+1 < 0 or last_1 == len(line)-1 or count_1-count_0 >= 3:
  192. return True
  193. return False
  194. def getsimilarity(line, line1):
  195. same_count = 0
  196. for item, item1 in zip(line,line1):
  197. if item[1] == item1[1]:
  198. same_count += 1
  199. return same_count/len(line)
  200. def selfrepair(inner_table,index,dye_set,key_set):
  201. """
  202. @summary: 计算每个节点受到的挤压度来判断是否需要染色
  203. """
  204. # print("B",inner_table[index])
  205. min_presure = 3
  206. list_dye = []
  207. first = None
  208. count = 0
  209. # temp_set = set()
  210. temp_set = set(['~~']) # 2023/10/10纠正236239652 受让单位识别不到表头; 受让单位,明细用途:用途名称:陵川县民政局,
  211. _index = 0
  212. for item in inner_table[index]:
  213. if first is None:
  214. first = item[1]
  215. if item[0] not in temp_set:
  216. count += 1
  217. temp_set.add(item[0])
  218. else:
  219. if first == item[1]:
  220. if item[0] not in temp_set:
  221. temp_set.add(item[0])
  222. count += 1
  223. else:
  224. list_dye.append([first,count,_index])
  225. first = item[1]
  226. temp_set.add(item[0])
  227. count = 1
  228. _index += 1
  229. list_dye.append([first,count,_index])
  230. if len(list_dye)>1:
  231. begin = 0
  232. end = 0
  233. for i in range(len(list_dye)):
  234. end = list_dye[i][2]
  235. dye_flag = False
  236. # 首尾要求压力减一
  237. if i==0:
  238. if list_dye[i+1][1]-list_dye[i][1]+1>=min_presure-1:
  239. dye_flag = True
  240. dye_type = list_dye[i+1][0]
  241. elif i==len(list_dye)-1:
  242. if list_dye[i-1][1]-list_dye[i][1]+1>=min_presure-1:
  243. dye_flag = True
  244. dye_type = list_dye[i-1][0]
  245. else:
  246. if list_dye[i][1]>1:
  247. if 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 list_dye[i-1][1]-list_dye[i][1]+1>=min_presure:
  251. dye_flag = True
  252. dye_type = list_dye[i-1][0]
  253. else:
  254. if list_dye[i+1][1]+list_dye[i-1][1]-list_dye[i][1]+1>=min_presure:
  255. dye_flag = True
  256. dye_type = list_dye[i+1][0]
  257. if list_dye[i+1][1]+list_dye[i-1][1]-list_dye[i][1]+1>=min_presure:
  258. dye_flag = True
  259. dye_type = list_dye[i-1][0]
  260. if dye_flag:
  261. for h in range(begin,end):
  262. inner_table[index][h][1] = dye_type
  263. dye_set.add((inner_table[index][h][0],dye_type))
  264. key_set.add(inner_table[index][h][0])
  265. begin = end
  266. # print("E",inner_table[index])
  267. def otherrepair(inner_table,index,dye_set,key_set):
  268. list_provide_repair = []
  269. if index==0 and len(inner_table)>1:
  270. list_provide_repair.append(index+1)
  271. elif index==len(inner_table)-1:
  272. list_provide_repair.append(index-1)
  273. else:
  274. list_provide_repair.append(index+1)
  275. list_provide_repair.append(index-1)
  276. for provide_index in list_provide_repair:
  277. if not repairNeeded(inner_table[provide_index]):
  278. same_prob = getsimilarity(inner_table[index], inner_table[provide_index])
  279. if same_prob>=0.8:
  280. for i in range(len(inner_table[provide_index])):
  281. if inner_table[index][i][1]!=inner_table[provide_index][i][1]:
  282. dye_set.add((inner_table[index][i][0],inner_table[provide_index][i][1]))
  283. key_set.add(inner_table[index][i][0])
  284. inner_table[index][i][1] = inner_table[provide_index][i][1]
  285. elif same_prob<=0.2:
  286. for i in range(len(inner_table[provide_index])):
  287. if inner_table[index][i][1]==inner_table[provide_index][i][1]:
  288. dye_set.add((inner_table[index][i][0],inner_table[provide_index][i][1]))
  289. key_set.add(inner_table[index][i][0])
  290. inner_table[index][i][1] = 0 if inner_table[provide_index][i][1] ==1 else 1
  291. len_dye_set = len(dye_set)
  292. height = len(inner_table)
  293. for i in range(height):
  294. if repairNeeded(inner_table[i]):
  295. selfrepair(inner_table, i, dye_set, key_set)
  296. #otherrepair(inner_table,i,dye_set,key_set)
  297. for h in range(len(inner_table)):
  298. for w in range(len(inner_table[0])):
  299. if inner_table[h][w][0] in key_set:
  300. for item in dye_set:
  301. if inner_table[h][w][0] == item[0]:
  302. inner_table[h][w][1] = item[1]
  303. # 如果两个set长度不相同,则有同一个key被反复染色,将导致无限迭代
  304. if len(dye_set) != len(key_set):
  305. for i in range(height):
  306. if repairNeeded(inner_table[i]):
  307. selfrepair(inner_table,i,dye_set,key_set)
  308. #otherrepair(inner_table,i,dye_set,key_set)
  309. return
  310. if len(dye_set) == len_dye_set:
  311. '''
  312. for i in range(height):
  313. if repairNeeded(inner_table[i]):
  314. otherrepair(inner_table,i,dye_set,key_set)
  315. '''
  316. return
  317. repairTable(inner_table, dye_set, key_set)
  318. def repair_table2(inner_table, show=0, row_no=0):
  319. """
  320. @summary: 修复表头识别,将明显错误的进行修正
  321. """
  322. # 循环处理单元格,一次获取需要的
  323. one_head_index_list = []
  324. zero_head_index_list = []
  325. all_head_index_list = []
  326. for i in range(len(inner_table)):
  327. head_cnt = 0
  328. for j in range(len(inner_table[i])):
  329. # 删除前后逗号
  330. inner_table[i][j][0] = re.sub('^[,,]+', '', inner_table[i][j][0])
  331. inner_table[i][j][0] = re.sub('[,,]+$', '', inner_table[i][j][0])
  332. # 统计表头数
  333. if inner_table[i][j][1] == 1:
  334. head_cnt += 1
  335. # 表头数list
  336. if head_cnt == 0:
  337. zero_head_index_list.append(i)
  338. elif head_cnt == 1:
  339. one_head_index_list.append(i)
  340. elif head_cnt == len(inner_table[i]):
  341. all_head_index_list.append(i)
  342. # 修复冒号在文本中间的,不能作为表头;(冒号后面需多个字)
  343. # 冒号在括号中的除外
  344. # 冒号在最后的,判断后一个格子是否有重复的文字
  345. for i in range(len(inner_table)):
  346. for j in range(len(inner_table[i])):
  347. _text = inner_table[i][j][0]
  348. if len(_text) >= 3 and inner_table[i][j][1] == 1:
  349. match = re.search('[::]', _text)
  350. if match:
  351. start_index, end_index = match.span()
  352. if start_index == 0:
  353. continue
  354. if end_index == len(_text):
  355. if len(inner_table[i]) == 2 and j <= len(inner_table[i]) - 2 and (_text in inner_table[i][j+1][0] or inner_table[i][j+1][0] in _text):
  356. inner_table[i][j][1] = 0
  357. inner_table[i][j+1][1] = 0
  358. else:
  359. continue
  360. if re.search('[((]', _text[:start_index]) and re.search('[))]', _text[end_index:]):
  361. continue
  362. m1 = re.search('[\u4e00-\u9fa50-9a-zA-Z]', _text[:start_index])
  363. m2 = re.search('[\u4e00-\u9fa50-9a-zA-Z]', _text[end_index:])
  364. if m1 and m2 and (len(m2.group()) >= 2 or m2.group() in ['是', '否']):
  365. inner_table[i][j][1] = 0
  366. if show:
  367. print('inner_table[i]1', inner_table[row_no])
  368. # 修复实际只有几列,但有一列由于重复占了太多行表头识别错误
  369. # for i in range(len(inner_table)):
  370. # head_flag_dict = {}
  371. # for j in range(len(inner_table[i])):
  372. # if inner_table[i][j][0] in head_flag_dict.keys():
  373. # head_flag_dict[inner_table[i][j][0]] += [inner_table[i][j][1]]
  374. # else:
  375. # head_flag_dict[inner_table[i][j][0]] = [inner_table[i][j][1]]
  376. #
  377. # if len(head_flag_dict.keys()) == 2:
  378. # col_flag = None
  379. # col_value = None
  380. # for key in head_flag_dict.keys():
  381. # flag_list = head_flag_dict[key]
  382. # if len(flag_list) >= 4 and len(set(flag_list)) == 2 and len(set(flag_list[1:])) == 1:
  383. # col_flag = flag_list[0]
  384. # col_value = key
  385. # break
  386. #
  387. # if col_flag is not None:
  388. # for j in range(len(inner_table[i])):
  389. # if inner_table[i][j][0] == col_value:
  390. # inner_table[i][j][1] = col_flag
  391. # 多个重复列的预测值不同,以第一个为准
  392. for i in range(len(inner_table)):
  393. col = inner_table[i][0]
  394. for j in range(len(inner_table[i])):
  395. if inner_table[i][j][0] == col[0]:
  396. if inner_table[i][j][1] != col[1]:
  397. inner_table[i][j][1] = col[1]
  398. else:
  399. col = inner_table[i][j]
  400. if show:
  401. print('inner_table[i]2', inner_table[row_no])
  402. # 修复多个重复的单元格表头不一致
  403. # for i in range(len(inner_table)):
  404. # for j in range(len(inner_table[i])-1):
  405. # only_chinese1 = ''.join(re.findall('[\u4e00-\u9fa5]+', inner_table[i][j][0]))
  406. # only_chinese2 = ''.join(re.findall('[\u4e00-\u9fa5]+', inner_table[i][j+1][0]))
  407. # if only_chinese1 == only_chinese2 and inner_table[i][j][1] != inner_table[i][j+1][1]:
  408. # inner_table[i][j][1] = 1
  409. # inner_table[i][j+1][1] = 1
  410. # if show:
  411. # print('inner_table[i]3', inner_table[row_no])
  412. # # 修复一行几乎都是表头,个别不是;或者一行几乎都是非表头,个别是
  413. # for i in range(len(inner_table)):
  414. # head_dict = {}
  415. # not_head_dict = {}
  416. # for j in range(len(inner_table[i])):
  417. # if inner_table[i][j][1] == 1:
  418. # if inner_table[i][j][0] not in head_dict:
  419. # head_dict[inner_table[i][j][0]] = 1
  420. # else:
  421. # if inner_table[i][j][0] not in not_head_dict:
  422. # not_head_dict[inner_table[i][j][0]] = 1
  423. #
  424. # # 非表头:表头 <= 1:3
  425. # # if len(head_dict.keys()) > 0 and len(not_head_dict.keys()) / len(head_dict.keys()) <= 1/3 and len(head_dict.keys()) >= 3:
  426. # # for j in range(len(inner_table[i])):
  427. # # if len(re.sub(' ', '', inner_table[i][j][0])) > 0:
  428. # # inner_table[i][j][1] = 1
  429. #
  430. # # 表头数一个且非表头数大于2且上一行都是表头
  431. # if i > 0 and len(head_dict.keys()) == 1 and len(not_head_dict.keys()) >= 2 and inner_table[i][0][1] == 0:
  432. # last_row = inner_table[i-1]
  433. # col_list = []
  434. # for j in range(len(last_row)):
  435. # if len(re.sub(' ', '', last_row[j][0])) > 0:
  436. # if last_row[j][1] == 0:
  437. # col_list = []
  438. # break
  439. # col_list.append(last_row[j][0])
  440. # if col_list:
  441. # col_list = list(set(col_list))
  442. # if len(col_list) > 2:
  443. # for j in range(len(inner_table[i])):
  444. # if inner_table[i][j][1] == 1:
  445. # inner_table[i][j][1] = 0
  446. # 一整个大表格,第一行为表头,下面行中有个别格子被识别为表头
  447. # 候选人后面修复
  448. for index in one_head_index_list:
  449. if (index - 1 in zero_head_index_list and index - 2 in zero_head_index_list) \
  450. or (index - 1 in zero_head_index_list and index - 2 in all_head_index_list) \
  451. or (index - 1 in all_head_index_list):
  452. for j in range(len(inner_table[index])):
  453. inner_table[index][j][1] = 0
  454. zero_head_index_list.append(index)
  455. if show:
  456. print('inner_table[i]4', inner_table[row_no])
  457. # 修复第一第二第三中标候选人作为表头
  458. first_tenderer = ['第一中标候选人', '第一中标人', '第一中标(成交)人', '第一候选人']
  459. second_tenderer = ['第二中标候选人', '第二中标(成交)候选人', '第二候选人']
  460. third_tenderer = ['第三中标候选人', '第三中标(成交)候选人', '第三候选人']
  461. # n1 next one, n2 next two, l1 last one, l2 last two
  462. for i in range(len(inner_table)):
  463. row = inner_table[i]
  464. n1_row, n2_row = None, None
  465. if i+1 < len(inner_table):
  466. n1_row = inner_table[i+1]
  467. if i+2 < len(inner_table):
  468. n2_row = inner_table[i+2]
  469. for j in range(len(row)):
  470. row_col = row[j]
  471. n1_row_col, n2_row_col = None, None
  472. row_n1_col, row_n2_col = None, None
  473. n1_row_n1_col, n2_row_n1_col, n1_row_n2_col = None, None, None
  474. if n1_row:
  475. n1_row_col = n1_row[j]
  476. if n2_row:
  477. n2_row_col = n2_row[j]
  478. if j+1 < len(row):
  479. row_n1_col = row[j+1]
  480. if j+2 < len(row):
  481. row_n2_col = row[j+2]
  482. if n1_row and j+1 < len(n1_row):
  483. n1_row_n1_col = n1_row[j+1]
  484. if n2_row and j+1 < len(n2_row):
  485. n2_row_n1_col = n2_row[j+1]
  486. if n1_row and j+2 < len(n1_row):
  487. n1_row_n2_col = n1_row[j+2]
  488. # 连续作为行表头
  489. if row_col[0] in first_tenderer and row_n1_col and row_n1_col[1] == 0:
  490. if n1_row_col and n1_row_col[0] in second_tenderer and n1_row_n1_col and n1_row_n1_col[1] == 0:
  491. inner_table[i][j][1] = 1
  492. inner_table[i+1][j][1] = 1
  493. if n2_row_col and n2_row_col[0] in third_tenderer and n2_row_n1_col and n2_row_n1_col[1] == 0:
  494. inner_table[i+2][j][1] = 1
  495. # 连续作为列表头
  496. if row_col[0] in first_tenderer and n1_row_col and n1_row_col[1] == 0:
  497. if row_n1_col and row_n1_col[0] in second_tenderer and n1_row_n1_col and n1_row_n1_col[1] == 0:
  498. inner_table[i][j][1] = 1
  499. inner_table[i][j+1][1] = 1
  500. if row_n2_col and row_n2_col[0] in third_tenderer and n1_row_n2_col and n1_row_n2_col[1] == 0:
  501. inner_table[i][j+2][1] = 1
  502. if show:
  503. print('inner_table[i]5', inner_table[row_no])
  504. # 修复表头关键词未作为表头
  505. # 文本匹配关键词,直接作为表头
  506. head_keyword = ['供应商', '总价']
  507. # 末尾匹配关键词且前一列为表头且与前一列文本不同,直接不做表头
  508. head_keyword2 = ['管理中心', '有限公司', '项目采购', ]
  509. # 开头匹配关键词,直接不做表头
  510. head_keyword3 = ['详见', '选定', '咨询服务', '标准物资', '电汇', '承兑']
  511. # 文本匹配关键词且前一列为表头,直接作为表头
  512. head_keyword4 = ['综合排名']
  513. # 文本在关键词中,直接不做表头
  514. head_keyword5 = ['殡葬用地']
  515. # n1 next one, n2 next two, l1 last one, l2 last two
  516. for i in range(len(inner_table)):
  517. row = inner_table[i]
  518. for j in range(len(row)):
  519. row_col = row[j]
  520. row_l1_col = None
  521. if j-1 > 0:
  522. row_l1_col = row[j-1]
  523. match = re.search('[\u4e00-\u9fa50-9a-zA-Z::]+', row_col[0])
  524. if inner_table[i][j][1] == 0 and match and match.group() in head_keyword:
  525. inner_table[i][j][1] = 1
  526. for key in head_keyword2:
  527. match = re.search(key+'$', row_col[0])
  528. if j > 0 and row_l1_col and row_l1_col[1] == 1 and row_l1_col[0] != row_col[0] and match and row_col[1] == 1:
  529. inner_table[i][j][1] = 0
  530. for key in head_keyword3:
  531. match = re.search('^'+key, row_col[0])
  532. if match and row_col[1] == 1:
  533. inner_table[i][j][1] = 0
  534. for key in head_keyword4:
  535. match = re.search(key, row_col[0])
  536. if j > 0 and row_l1_col and row_l1_col[1] == 1 and match and row_col[1] == 0:
  537. inner_table[i][j][1] = 1
  538. if row_col[0] in head_keyword5:
  539. inner_table[i][j][1] = 0
  540. if show:
  541. print('inner_table[i]6', inner_table[row_no])
  542. # 修复姓名被作为表头 # 2023-02-10 取消修复,避免项目名称、编号,单位、单价等作为了非表头
  543. # surname = [
  544. # "赵", "钱", "孙", "李", "周", "吴", "郑", "王", "冯", "陈", "褚", "卫", "蒋", "沈", "韩", "杨", "朱", "秦", "尤", "许", "何", "吕", "施", "张", "孔", "曹", "严", "华", "金", "魏", "陶", "姜", "戚", "谢", "邹", "喻", "柏", "水", "窦", "章", "云", "苏", "潘", "葛", "奚", "范", "彭", "郎", "鲁", "韦", "昌", "马", "苗", "凤", "花", "方", "俞", "任", "袁", "柳", "酆", "鲍", "史", "唐", "费", "廉", "岑", "薛", "雷", "贺", "倪", "汤", "滕", "殷", "罗", "毕", "郝", "邬", "安", "常", "乐", "于", "时", "傅", "皮", "卞", "齐", "康", "伍", "余", "元", "卜", "顾", "孟", "平", "黄", "和", "穆", "萧", "尹", "姚", "邵", "湛", "汪", "祁", "毛", "禹", "狄", "米", "贝", "明", "臧", "计", "伏", "成", "戴", "谈", "宋", "茅", "庞", "熊", "纪", "舒", "屈", "项", "祝", "董", "梁", "杜", "阮", "蓝", "闵", "席", "季", "麻", "强", "贾", "路", "娄", "危", "江", "童", "颜", "郭", "梅", "盛", "林", "刁", "钟", "徐", "邱", "骆", "高", "夏", "蔡", "田", "樊", "胡", "凌", "霍", "虞", "万", "支", "柯", "昝", "管", "卢", "莫", "经", "房", "裘", "缪", "干", "解", "应", "宗", "丁", "宣", "贲", "邓", "郁", "单", "杭", "洪", "包", "诸", "左", "石", "崔", "吉", "钮", "龚", "程", "嵇", "邢", "滑", "裴", "陆", "荣", "翁", "荀", "羊", "於", "惠", "甄", "麴", "家", "封", "芮", "羿", "储", "靳", "汲", "邴", "糜", "松", "井", "段", "富", "巫", "乌", "焦", "巴", "弓", "牧", "隗", "山", "谷", "车", "侯", "宓", "蓬", "全", "郗", "班", "仰", "秋", "仲", "伊", "宫", "宁", "仇", "栾", "暴", "甘", "钭", "厉", "戎", "祖", "武", "符", "刘", "景", "詹", "束", "龙", "叶", "幸", "司", "韶", "郜", "黎", "蓟", "薄", "印", "宿", "白", "怀", "蒲", "邰", "从", "鄂", "索", "咸", "籍", "赖", "卓", "蔺", "屠", "蒙", "池", "乔", "阴", "欎", "胥", "能", "苍", "双", "闻", "莘", "党", "翟", "谭", "贡", "劳", "逄", "姬", "申", "扶", "堵", "冉", "宰", "郦", "雍", "舄", "璩", "桑", "桂", "濮", "牛", "寿", "通", "边", "扈", "燕", "冀", "郏", "浦", "尚", "农", "温", "别", "庄", "晏", "柴", "瞿", "阎", "充", "慕", "连", "茹", "习", "宦", "艾", "鱼", "容", "向", "古", "易", "慎", "戈", "廖", "庾", "终", "暨", "居", "衡", "步", "都", "耿", "满", "弘", "匡", "国", "文", "寇", "广", "禄", "阙", "东", "殴", "殳", "沃", "利", "蔚", "越", "夔", "隆", "师", "巩", "厍", "聂", "晁", "勾", "敖", "融", "冷", "訾", "辛", "阚", "那", "简", "饶", "空", "曾", "毋", "沙", "乜", "养", "鞠", "须", "丰", "巢", "关", "蒯", "相", "查", "後", "荆", "红", "游", "竺", "权", "逯", "盖", "益", "桓", "公", "万俟", "司马", "上官", "欧阳", "夏侯", "诸葛", "闻人", "东方", "赫连", "皇甫", "尉迟", "公羊", "澹台", "公冶", "宗政", "濮阳", "淳于", "单于", "太叔", "申屠", "公孙", "仲孙", "轩辕", "令狐", "钟离", "宇文", "长孙", "慕容", "鲜于", "闾丘", "司徒", "司空", "亓官", "司寇", "仉", "督", "子车", "颛孙", "端木", "巫马", "公西", "漆雕", "乐正", "壤驷", "公良", "拓跋", "夹谷", "宰父", "谷梁", "晋", "楚", "闫", "法", "汝", "鄢", "涂", "钦", "段干", "百里", "东郭", "南门", "呼延", "归", "海", "羊舌", "微生", "岳", "帅", "缑", "亢", "况", "后", "有", "琴", "梁丘", "左丘", "东门", "西门", "商", "牟", "佘", "佴", "伯", "赏", "南宫", "墨", "哈", "谯", "笪", "年", "爱", "阳", "佟", "第五", "言", "福",
  545. # ]
  546. # for i in range(len(inner_table)):
  547. # for j in range(len(inner_table[i])):
  548. # if inner_table[i][j][1] == 1 \
  549. # and 2 <= len(inner_table[i][j][0]) <= 4 \
  550. # and (inner_table[i][j][0][0] in surname or inner_table[i][j][0][:2] in surname) \
  551. # and re.search("[^\u4e00-\u9fa5]", inner_table[i][j][0]) is None:
  552. # inner_table[i][j][1] = 0
  553. return inner_table
  554. def sliceTable(inner_table,fix_value="~~"):
  555. #进行分块
  556. height = len(inner_table)
  557. width = len(inner_table[0])
  558. head_list = []
  559. head_list.append(0)
  560. last_head = None
  561. last_is_same_value = False
  562. for h in range(height):
  563. is_all_key = True#是否是全表头行
  564. is_all_value = True#是否是全属性值
  565. is_same_with_lastHead = True#和上一行的结构是否相同
  566. is_same_value=True#一行的item都一样
  567. #is_same_first_item = True#与上一行的第一项是否相同
  568. same_value = inner_table[h][0][0]
  569. for w in range(width):
  570. if last_head is not None:
  571. if inner_table[h-1][w][0] != fix_value and inner_table[h-1][w][0] != "" and inner_table[h-1][w][1] == 0:
  572. is_all_key = False
  573. if inner_table[h][w][0]==1:
  574. is_all_value = False
  575. if inner_table[h][w][1]!= inner_table[h-1][w][1]:
  576. is_same_with_lastHead = False
  577. if inner_table[h][w][0]!=fix_value and inner_table[h][w][0]!=same_value:
  578. is_same_value = False
  579. else:
  580. if re.search("\d+",same_value) is not None:
  581. is_same_value = False
  582. if h>0 and inner_table[h][0][0]!=inner_table[h-1][0][0]:
  583. is_same_first_item = False
  584. last_head = h
  585. if last_is_same_value:
  586. last_is_same_value = is_same_value
  587. continue
  588. if is_same_value:
  589. # 该块只有表头一行不合法
  590. if h - head_list[-1] > 1:
  591. head_list.append(h)
  592. last_is_same_value = is_same_value
  593. continue
  594. if not is_all_key:
  595. if not is_same_with_lastHead:
  596. # 该块只有表头一行不合法
  597. if h - head_list[-1] > 1:
  598. head_list.append(h)
  599. head_list.append(height)
  600. return head_list
  601. def setHead_initem(inner_table,pat_head,fix_value="~~",prob_min=0.5):
  602. set_item = set()
  603. height = len(inner_table)
  604. width = len(inner_table[0])
  605. empty_set = set()
  606. for i in range(height):
  607. for j in range(width):
  608. item = inner_table[i][j][0]
  609. if item.strip()=="":
  610. empty_set.add(item)
  611. else:
  612. set_item.add(item)
  613. list_item = list(set_item)
  614. if list_item:
  615. x = []
  616. for item in list_item:
  617. x.append(getPredictor("form").encode(item))
  618. predict_y = getPredictor("form").predict(np.array(x),type="item")
  619. _dict = dict()
  620. for item,values in zip(list_item,list(predict_y)):
  621. _dict[item] = values[1]
  622. # print("##",item,values)
  623. #print(_dict)
  624. for i in range(height):
  625. for j in range(width):
  626. item = inner_table[i][j][0]
  627. if item not in empty_set:
  628. 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)
  629. # print("=====")
  630. # for item in inner_table:
  631. # print(item)
  632. # print("======")
  633. repairTable(inner_table)
  634. head_list = sliceTable(inner_table)
  635. return inner_table,head_list
  636. def set_head_model(inner_table, show=0):
  637. origin_inner_table = copy.deepcopy(inner_table)
  638. for i in range(len(inner_table)):
  639. for j in range(len(inner_table[i])):
  640. # 删掉单格前后符号,以免影响表头预测
  641. col = inner_table[i][j][0]
  642. col = re.sub("^[^\u4e00-\u9fa5a-zA-Z0-9]+", "", col)
  643. col = re.sub("[^\u4e00-\u9fa5a-zA-Z0-9]+$", "", col)
  644. inner_table[i][j] = col
  645. # 模型预测表头
  646. # predict_list = predict(inner_table)
  647. start_time = time.time()
  648. predict_list = predict(inner_table)
  649. # print('table head predict cost: ', time.time()-start_time)
  650. # 组合结果
  651. for i in range(len(inner_table)):
  652. for j in range(len(inner_table[i])):
  653. inner_table[i][j] = [origin_inner_table[i][j][0], int(predict_list[i][j])]
  654. if origin_inner_table[i][j][0] in ['主要环境影响及预防或者减轻不良环境影响的对策和措施', '建设单位或地方政府作出的相关环保承诺',
  655. '公众反馈意见的联系方式', '区县', '项目领域', '成本/收入', '覆盖倍数', '会计所', '律所','建设期',
  656. "发行时间" ,"批次" ,"发行额" ,"发行利率" ,"所属债券" ,"专项债作资本金发行额" ,"调整记录"] and predict_list[i][j]!=1:
  657. inner_table[i][j] = [origin_inner_table[i][j][0], 1]
  658. elif origin_inner_table[i][j][0] in ['经评审的最低评标价法'] and predict_list[i][j]==1:
  659. inner_table[i][j] = [origin_inner_table[i][j][0], 0]
  660. if show:
  661. print(json.dumps(inner_table, ensure_ascii=False))
  662. print("="*80)
  663. print("table_head before repair")
  664. for r in inner_table:
  665. print('row', r)
  666. print("="*80)
  667. # 表头修正
  668. # repairTable(inner_table)
  669. inner_table = table_head_repair_process(inner_table, docid)
  670. # 组合结果
  671. for i in range(len(inner_table)):
  672. for j in range(len(inner_table[i])):
  673. inner_table[i][j] = [origin_inner_table[i][j][0], int(inner_table[i][j][1])]
  674. if show:
  675. print("table_head after repair")
  676. for r in inner_table:
  677. print('row', r)
  678. print("="*80)
  679. # 按表头分割表格
  680. head_list = sliceTable(inner_table)
  681. return inner_table, head_list
  682. def setHead_incontext(inner_table,pat_head,fix_value="~~",prob_min=0.5):
  683. data_x,data_position = getPredictor("form").getModel("context").encode(inner_table)
  684. predict_y = getPredictor("form").getModel("context").predict(data_x)
  685. for _position,_y in zip(data_position,predict_y):
  686. _w = _position[0]
  687. _h = _position[1]
  688. if _y[1]>prob_min:
  689. inner_table[_h][_w][1] = 1
  690. else:
  691. inner_table[_h][_w][1] = 0
  692. _item = inner_table[_h][_w][0]
  693. if re.search(pat_head,_item) is not None and len(_item)<8:
  694. inner_table[_h][_w][1] = 1
  695. # print("=====")
  696. # for item in inner_table:
  697. # print(item)
  698. # print("======")
  699. height = len(inner_table)
  700. width = len(inner_table[0])
  701. for i in range(height):
  702. for j in range(width):
  703. if re.search("[::]$", inner_table[i][j][0]) and len(inner_table[i][j][0])<8:
  704. inner_table[i][j][1] = 1
  705. repairTable(inner_table)
  706. head_list = sliceTable(inner_table)
  707. # print("inner_table:",inner_table)
  708. return inner_table,head_list
  709. #设置表头
  710. def setHead_inline(inner_table,prob_min=0.64):
  711. pad_row = "@@"
  712. pad_col = "##"
  713. removePadding(inner_table, pad_row, pad_col)
  714. pad_pattern = re.compile(pad_row+"|"+pad_col)
  715. height = len(inner_table)
  716. width = len(inner_table[0])
  717. head_list = []
  718. head_list.append(0)
  719. #行表头
  720. is_head_last = False
  721. for i in range(height):
  722. is_head = False
  723. is_long_value = False
  724. #判断是否是全padding值
  725. is_same_value = True
  726. same_value = inner_table[i][0][0]
  727. for j in range(width):
  728. if inner_table[i][j][0]!=same_value and inner_table[i][j][0]!=pad_row:
  729. is_same_value = False
  730. break
  731. #predict is head or not with model
  732. temp_item = ""
  733. for j in range(width):
  734. temp_item += inner_table[i][j][0]+"|"
  735. temp_item = re.sub(pad_pattern,"",temp_item)
  736. form_prob = getPredictor("form").predict(formEncoding(temp_item,expand=True),type="line")
  737. if form_prob is not None:
  738. if form_prob[0][1]>prob_min:
  739. is_head = True
  740. else:
  741. is_head = False
  742. #print(temp_item,form_prob)
  743. if len(inner_table[i][0][0])>40:
  744. is_long_value = True
  745. if is_head or is_long_value or is_same_value:
  746. #不把连续表头分开
  747. if not is_head_last:
  748. head_list.append(i)
  749. if is_long_value or is_same_value:
  750. head_list.append(i+1)
  751. if is_head:
  752. for j in range(width):
  753. inner_table[i][j][1] = 1
  754. is_head_last = is_head
  755. head_list.append(height)
  756. #列表头
  757. for i in range(len(head_list)-1):
  758. head_begin = head_list[i]
  759. head_end = head_list[i+1]
  760. #最后一列不设置为列表头
  761. for i in range(width-1):
  762. is_head = False
  763. #predict is head or not with model
  764. temp_item = ""
  765. for j in range(head_begin,head_end):
  766. temp_item += inner_table[j][i][0]+"|"
  767. temp_item = re.sub(pad_pattern,"",temp_item)
  768. form_prob = getPredictor("form").predict(formEncoding(temp_item,expand=True),type="line")
  769. if form_prob is not None:
  770. if form_prob[0][1]>prob_min:
  771. is_head = True
  772. else:
  773. is_head = False
  774. if is_head:
  775. for j in range(head_begin,head_end):
  776. inner_table[j][i][1] = 2
  777. addPadding(inner_table, pad_row, pad_col)
  778. return inner_table,head_list
  779. #设置表头
  780. def setHead_withRule(inner_table,pattern,pat_value,count):
  781. height = len(inner_table)
  782. width = len(inner_table[0])
  783. head_list = []
  784. head_list.append(0)
  785. #行表头
  786. is_head_last = False
  787. for i in range(height):
  788. set_match = set()
  789. is_head = False
  790. is_long_value = False
  791. is_same_value = True
  792. same_value = inner_table[i][0][0]
  793. for j in range(width):
  794. if inner_table[i][j][0]!=same_value:
  795. is_same_value = False
  796. break
  797. for j in range(width):
  798. if re.search(pat_value,inner_table[i][j][0]) is not None:
  799. is_head = False
  800. break
  801. str_find = re.findall(pattern,inner_table[i][j][0])
  802. if len(str_find)>0:
  803. set_match.add(inner_table[i][j][0])
  804. if len(set_match)>=count:
  805. is_head = True
  806. if len(inner_table[i][0][0])>40:
  807. is_long_value = True
  808. if is_head or is_long_value or is_same_value:
  809. if not is_head_last:
  810. head_list.append(i)
  811. if is_head:
  812. for j in range(width):
  813. inner_table[i][j][1] = 1
  814. is_head_last = is_head
  815. head_list.append(height)
  816. #列表头
  817. for i in range(len(head_list)-1):
  818. head_begin = head_list[i]
  819. head_end = head_list[i+1]
  820. #最后一列不设置为列表头
  821. for i in range(width-1):
  822. set_match = set()
  823. is_head = False
  824. for j in range(head_begin,head_end):
  825. if re.search(pat_value,inner_table[j][i][0]) is not None:
  826. is_head = False
  827. break
  828. str_find = re.findall(pattern,inner_table[j][i][0])
  829. if len(str_find)>0:
  830. set_match.add(inner_table[j][i][0])
  831. if len(set_match)>=count:
  832. is_head = True
  833. if is_head:
  834. for j in range(head_begin,head_end):
  835. inner_table[j][i][1] = 2
  836. return inner_table,head_list
  837. #取得表格的处理方向
  838. def getDirect(inner_table,begin,end):
  839. '''
  840. column_head = set()
  841. row_head = set()
  842. widths = len(inner_table[0])
  843. for height in range(begin,end):
  844. for width in range(widths):
  845. if inner_table[height][width][1] ==1:
  846. row_head.add(height)
  847. if inner_table[height][width][1] ==2:
  848. column_head.add(width)
  849. company_pattern = re.compile("公司")
  850. if 0 in column_head and begin not in row_head:
  851. return "column"
  852. if 0 in column_head and begin in row_head:
  853. for height in range(begin,end):
  854. count = 0
  855. count_flag = True
  856. for width_index in range(width):
  857. if inner_table[height][width_index][1]==0:
  858. if re.search(company_pattern,inner_table[height][width_index][0]) is not None:
  859. count += 1
  860. else:
  861. count_flag = False
  862. if count_flag and count>=2:
  863. return "column"
  864. return "row"
  865. '''
  866. count_row_keys = 0
  867. count_column_keys = 0
  868. width = len(inner_table[0])
  869. if begin<end:
  870. for w in range(len(inner_table[begin])):
  871. if inner_table[begin][w][1]!=0:
  872. count_row_keys += 1
  873. for h in range(begin,end):
  874. if inner_table[h][0][1]!=0:
  875. count_column_keys += 1
  876. company_pattern = re.compile("有限(责任)?公司")
  877. for height in range(begin,end):
  878. count_set = set()
  879. count_flag = True
  880. for width_index in range(width):
  881. if inner_table[height][width_index][1]==0:
  882. if re.search(company_pattern,inner_table[height][width_index][0]) is not None:
  883. count_set.add(inner_table[height][width_index][0])
  884. else:
  885. count_flag = False
  886. if count_flag and len(count_set)>=2:
  887. return "column"
  888. # if count_column_keys>count_row_keys: #2022/2/15 此项不够严谨,造成很多错误,故取消
  889. # return "column"
  890. return "row"
  891. #根据表格处理方向生成句子,
  892. def getTableText(inner_table,head_list,key_direct=False):
  893. # packPattern = "(标包|[标包][号段名])"
  894. packPattern = "(标包|标的|标项|品目|[标包][号段名]|((项目|物资|设备|场次|标段|标的|产品)(名称)))" # 2020/11/23 大网站规则,补充采购类包名
  895. rankPattern = "(排名|排序|名次|序号|评标结果|评审结果|是否中标|推荐意见|评标情况|推荐顺序|选取(情况|说明))" # 2020/11/23 大网站规则,添加序号为排序
  896. entityPattern = "((候选|[中投]标|报价)(单位|公司|人|供应商))|供应商名称"
  897. moneyPattern = "([中投]标|报价)(金额|价)"
  898. height = len(inner_table)
  899. width = len(inner_table[0])
  900. text = ""
  901. for head_i in range(len(head_list)-1):
  902. head_begin = head_list[head_i]
  903. head_end = head_list[head_i+1]
  904. direct = getDirect(inner_table, head_begin, head_end)
  905. #若只有一行,则直接按行读取
  906. if head_end-head_begin==1:
  907. text_line = ""
  908. for i in range(head_begin,head_end):
  909. for w in range(len(inner_table[i])):
  910. if inner_table[i][w][1]==1:
  911. _punctuation = ":"
  912. else:
  913. _punctuation = "," #2021/12/15 统一为中文标点,避免 206893924 国际F座1108,1,009,197.49元
  914. if w>0:
  915. if inner_table[i][w][0]!= inner_table[i][w-1][0]:
  916. text_line += inner_table[i][w][0]+_punctuation
  917. else:
  918. text_line += inner_table[i][w][0]+_punctuation
  919. text_line = text_line+"。" if text_line!="" else text_line
  920. text += text_line
  921. else:
  922. #构建一个共现矩阵
  923. table_occurence = []
  924. for i in range(head_begin,head_end):
  925. line_oc = []
  926. for j in range(width):
  927. cell = inner_table[i][j]
  928. line_oc.append({"text":cell[0],"type":cell[1],"occu_count":0,"left_head":"","top_head":"","left_dis":0,"top_dis":0})
  929. table_occurence.append(line_oc)
  930. occu_height = len(table_occurence)
  931. occu_width = len(table_occurence[0]) if len(table_occurence)>0 else 0
  932. #为每个属性值寻找表头
  933. for i in range(occu_height):
  934. for j in range(occu_width):
  935. cell = table_occurence[i][j]
  936. #是属性值
  937. if cell["type"]==0 and cell["text"]!="":
  938. left_head = ""
  939. top_head = ""
  940. find_flag = False
  941. temp_head = ""
  942. for loop_i in range(1,i+1):
  943. if not key_direct:
  944. key_values = [1,2]
  945. else:
  946. key_values = [1]
  947. if table_occurence[i-loop_i][j]["type"] in key_values:
  948. if find_flag:
  949. if table_occurence[i-loop_i][j]["text"]!=temp_head:
  950. top_head = table_occurence[i-loop_i][j]["text"]+":"+top_head
  951. else:
  952. top_head = table_occurence[i-loop_i][j]["text"]+":"+top_head
  953. find_flag = True
  954. temp_head = table_occurence[i-loop_i][j]["text"]
  955. table_occurence[i-loop_i][j]["occu_count"] += 1
  956. else:
  957. #找到表头后遇到属性值就返回
  958. if find_flag:
  959. break
  960. cell["top_head"] += top_head
  961. find_flag = False
  962. temp_head = ""
  963. for loop_j in range(1,j+1):
  964. if not key_direct:
  965. key_values = [1,2]
  966. else:
  967. key_values = [2]
  968. if table_occurence[i][j-loop_j]["type"] in key_values:
  969. if find_flag:
  970. if table_occurence[i][j-loop_j]["text"]!=temp_head:
  971. left_head = table_occurence[i][j-loop_j]["text"]+":"+left_head
  972. else:
  973. left_head = table_occurence[i][j-loop_j]["text"]+":"+left_head
  974. find_flag = True
  975. temp_head = table_occurence[i][j-loop_j]["text"]
  976. table_occurence[i][j-loop_j]["occu_count"] += 1
  977. else:
  978. if find_flag:
  979. break
  980. cell["left_head"] += left_head
  981. if direct=="row":
  982. for i in range(occu_height):
  983. pack_text = ""
  984. rank_text = ""
  985. entity_text = ""
  986. text_line = ""
  987. money_text = ""
  988. #在同一句话中重复的可以去掉
  989. text_set = set()
  990. head = ""
  991. last_text = ""
  992. for j in range(width):
  993. cell = table_occurence[i][j]
  994. if cell["type"]==0 or (cell["type"]==1 and cell["occu_count"]==0):
  995. cell = table_occurence[i][j]
  996. head = (cell["top_head"]+":") if len(cell["top_head"])>0 else ""
  997. if re.search("[单报标限总]价|金额|成交报?价|报价|供应商|候选人|中标人|[利费]率|负责人|工期|服务(期限?|年限|时间|日期|周期)|(履约|履行)期限|合同(期限?|(完成|截止)(日期|时间))", head):
  998. head = cell["left_head"] + head
  999. else:
  1000. head += cell["left_head"]
  1001. if str(head+cell["text"]) in text_set:
  1002. continue
  1003. if re.search(packPattern,head) is not None:
  1004. pack_text += head+cell["text"]+","
  1005. elif re.search(rankPattern,head) is not None and re.search('(排名|排序|名次|顺序):?第?[\d一二三]', rank_text)==None: # 2020/11/23 大网站规则发现问题,if 改elif 20240620修复同时有排名及评标情况造成错误
  1006. #排名替换为同一种表达
  1007. rank_text += head+cell["text"]+","
  1008. #print(rank_text)
  1009. elif re.search(entityPattern,head) is not None:
  1010. entity_text += head+cell["text"]+","
  1011. #print(entity_text)
  1012. else:
  1013. if re.search(moneyPattern,head) is not None and entity_text!="":
  1014. money_text += head+cell["text"]+","
  1015. else:
  1016. text_line += head+cell["text"]+","
  1017. text_set.add(str(head+cell["text"]))
  1018. last_text = cell['text']
  1019. tr_text = pack_text+rank_text+entity_text+money_text+text_line
  1020. text += pack_text+rank_text+entity_text+money_text+text_line
  1021. # text = text[:-1] + "。" if len(text) > 0 else text
  1022. if len(text_set-set([' ']))==1 and head == '' and len(last_text)< 25: # 修复367694716分两行表达
  1023. text = text if re.search('\w$', text[:-1]) else text[:-1]
  1024. elif (width == 2 or len(text_set)==1) and head != '' and len(tr_text)<50: # 修复494731937只有两行的,分句不合理
  1025. text = text if re.search('\w$', text[:-1]) else text[:-1]
  1026. else:
  1027. text = text[:-1] + "。"
  1028. else:
  1029. for j in range(occu_width):
  1030. pack_text = ""
  1031. rank_text = ""
  1032. entity_text = ""
  1033. text_line = ""
  1034. text_set = set()
  1035. for i in range(occu_height):
  1036. cell = table_occurence[i][j]
  1037. if cell["type"]==0 or (cell["type"]==1 and cell["occu_count"]==0):
  1038. cell = table_occurence[i][j]
  1039. head = (cell["left_head"]+"") if len(cell["left_head"])>0 else ""
  1040. if re.search("[单报标限总]价|金额|成交报?价|报价|供应商|候选人|中标人|[利费]率|负责人|工期|服务(期限?|年限|时间|日期|周期)|(履约|履行)期限|合同(期限?|(完成|截止)(日期|时间))", head):
  1041. head = cell["top_head"] + head
  1042. else:
  1043. head += cell["top_head"]
  1044. if str(head+cell["text"]) in text_set:
  1045. continue
  1046. if re.search(packPattern,head) is not None:
  1047. pack_text += head+cell["text"]+","
  1048. elif re.search(rankPattern,head) is not None: # 2020/11/23 大网站规则发现问题,if 改elif
  1049. #排名替换为同一种表达
  1050. rank_text += head+cell["text"]+","
  1051. #print(rank_text)
  1052. elif re.search(entityPattern,head) is not None and \
  1053. re.search('业绩|资格|条件',head)==None and re.search('业绩',cell["text"])==None : #2021/10/19 解决包含业绩的行调到前面问题
  1054. entity_text += head+cell["text"]+","
  1055. #print(entity_text)
  1056. else:
  1057. text_line += head+cell["text"]+","
  1058. text_set.add(str(head+cell["text"]))
  1059. text += pack_text+rank_text+entity_text+text_line
  1060. text = text[:-1]+"。" if len(text)>0 else text
  1061. # if direct=="row":
  1062. # for i in range(head_begin,head_end):
  1063. # pack_text = ""
  1064. # rank_text = ""
  1065. # entity_text = ""
  1066. # text_line = ""
  1067. # #在同一句话中重复的可以去掉
  1068. # text_set = set()
  1069. # for j in range(width):
  1070. # cell = inner_table[i][j]
  1071. # #是属性值
  1072. # if cell[1]==0 and cell[0]!="":
  1073. # head = ""
  1074. #
  1075. # find_flag = False
  1076. # temp_head = ""
  1077. # for loop_i in range(0,i+1-head_begin):
  1078. # if not key_direct:
  1079. # key_values = [1,2]
  1080. # else:
  1081. # key_values = [1]
  1082. # if inner_table[i-loop_i][j][1] in key_values:
  1083. # if find_flag:
  1084. # if inner_table[i-loop_i][j][0]!=temp_head:
  1085. # head = inner_table[i-loop_i][j][0]+":"+head
  1086. # else:
  1087. # head = inner_table[i-loop_i][j][0]+":"+head
  1088. # find_flag = True
  1089. # temp_head = inner_table[i-loop_i][j][0]
  1090. # else:
  1091. # #找到表头后遇到属性值就返回
  1092. # if find_flag:
  1093. # break
  1094. #
  1095. # find_flag = False
  1096. # temp_head = ""
  1097. #
  1098. #
  1099. #
  1100. # for loop_j in range(1,j+1):
  1101. # if not key_direct:
  1102. # key_values = [1,2]
  1103. # else:
  1104. # key_values = [2]
  1105. # if inner_table[i][j-loop_j][1] in key_values:
  1106. # if find_flag:
  1107. # if inner_table[i][j-loop_j][0]!=temp_head:
  1108. # head = inner_table[i][j-loop_j][0]+":"+head
  1109. # else:
  1110. # head = inner_table[i][j-loop_j][0]+":"+head
  1111. # find_flag = True
  1112. # temp_head = inner_table[i][j-loop_j][0]
  1113. # else:
  1114. # if find_flag:
  1115. # break
  1116. #
  1117. # if str(head+inner_table[i][j][0]) in text_set:
  1118. # continue
  1119. # if re.search(packPattern,head) is not None:
  1120. # pack_text += head+inner_table[i][j][0]+","
  1121. # elif re.search(rankPattern,head) is not None: # 2020/11/23 大网站规则发现问题,if 改elif
  1122. # #排名替换为同一种表达
  1123. # rank_text += head+inner_table[i][j][0]+","
  1124. # #print(rank_text)
  1125. # elif re.search(entityPattern,head) is not None:
  1126. # entity_text += head+inner_table[i][j][0]+","
  1127. # #print(entity_text)
  1128. # else:
  1129. # text_line += head+inner_table[i][j][0]+","
  1130. # text_set.add(str(head+inner_table[i][j][0]))
  1131. # text += pack_text+rank_text+entity_text+text_line
  1132. # text = text[:-1]+"。" if len(text)>0 else text
  1133. # else:
  1134. # for j in range(width):
  1135. #
  1136. # rank_text = ""
  1137. # entity_text = ""
  1138. # text_line = ""
  1139. # text_set = set()
  1140. # for i in range(head_begin,head_end):
  1141. # cell = inner_table[i][j]
  1142. # #是属性值
  1143. # if cell[1]==0 and cell[0]!="":
  1144. # find_flag = False
  1145. # head = ""
  1146. # temp_head = ""
  1147. #
  1148. # for loop_j in range(1,j+1):
  1149. # if not key_direct:
  1150. # key_values = [1,2]
  1151. # else:
  1152. # key_values = [2]
  1153. # if inner_table[i][j-loop_j][1] in key_values:
  1154. # if find_flag:
  1155. # if inner_table[i][j-loop_j][0]!=temp_head:
  1156. # head = inner_table[i][j-loop_j][0]+":"+head
  1157. # else:
  1158. # head = inner_table[i][j-loop_j][0]+":"+head
  1159. # find_flag = True
  1160. # temp_head = inner_table[i][j-loop_j][0]
  1161. # else:
  1162. # if find_flag:
  1163. # break
  1164. # find_flag = False
  1165. # temp_head = ""
  1166. # for loop_i in range(0,i+1-head_begin):
  1167. # if not key_direct:
  1168. # key_values = [1,2]
  1169. # else:
  1170. # key_values = [1]
  1171. # if inner_table[i-loop_i][j][1] in key_values:
  1172. # if find_flag:
  1173. # if inner_table[i-loop_i][j][0]!=temp_head:
  1174. # head = inner_table[i-loop_i][j][0]+":"+head
  1175. # else:
  1176. # head = inner_table[i-loop_i][j][0]+":"+head
  1177. # find_flag = True
  1178. # temp_head = inner_table[i-loop_i][j][0]
  1179. # else:
  1180. # if find_flag:
  1181. # break
  1182. # if str(head+inner_table[i][j][0]) in text_set:
  1183. # continue
  1184. # if re.search(rankPattern,head) is not None:
  1185. # rank_text += head+inner_table[i][j][0]+","
  1186. # #print(rank_text)
  1187. # elif re.search(entityPattern,head) is not None:
  1188. # entity_text += head+inner_table[i][j][0]+","
  1189. # #print(entity_text)
  1190. # else:
  1191. # text_line += head+inner_table[i][j][0]+","
  1192. # text_set.add(str(head+inner_table[i][j][0]))
  1193. # text += rank_text+entity_text+text_line
  1194. # text = text[:-1]+"。" if len(text)>0 else text
  1195. return text
  1196. def get_table_text_kv(inner_table, head_list, key_direct=False):
  1197. packPattern = "(标包|标的|标项|品目|[标包][号段名]|((项目|物资|设备|场次|标段|标的|产品)(名称)))" # 2020/11/23 大网站规则,补充采购类包名
  1198. rankPattern = "(排名|排序|名次|序号|评标结果|评审结果|是否中标|推荐意见|评标情况|推荐顺序|选取(情况|说明))" # 2020/11/23 大网站规则,添加序号为排序
  1199. entityPattern = "((候选|[中投]标|报价)(单位|公司|人|供应商))|供应商名称"
  1200. moneyPattern = "([中投]标|报价)(金额|价)"
  1201. width = len(inner_table[0])
  1202. text = ""
  1203. all_table_occurence = []
  1204. for head_i in range(len(head_list) - 1):
  1205. head_begin = head_list[head_i]
  1206. head_end = head_list[head_i + 1]
  1207. direct = getDirect(inner_table, head_begin, head_end)
  1208. # print(inner_table[head_begin:head_end])
  1209. # print('direct', direct)
  1210. # 构建一个共现矩阵
  1211. table_occurence = []
  1212. for i in range(head_begin, head_end):
  1213. line_oc = []
  1214. for j in range(width):
  1215. cell = inner_table[i][j]
  1216. line_oc.append(
  1217. {"text": cell[0], "type": cell[1], "occu_count": 0, "left_head": "", "top_head": "",
  1218. "left_dis": 0, "top_dis": 0,
  1219. "text_row_index": i, "text_col_index": j
  1220. })
  1221. table_occurence.append(line_oc)
  1222. occu_height = len(table_occurence)
  1223. occu_width = len(table_occurence[0]) if len(table_occurence) > 0 else 0
  1224. # 为每个属性值寻找表头
  1225. for i in range(occu_height):
  1226. for j in range(occu_width):
  1227. cell = table_occurence[i][j]
  1228. # 是属性值
  1229. if cell["type"] == 0 and cell["text"] != "":
  1230. left_head = ""
  1231. top_head = ""
  1232. find_flag = False
  1233. temp_head = ""
  1234. head_row_col_list = []
  1235. for loop_i in range(1, i + 1):
  1236. if not key_direct:
  1237. key_values = [1, 2]
  1238. else:
  1239. key_values = [1]
  1240. if table_occurence[i - loop_i][j]["type"] in key_values:
  1241. if find_flag:
  1242. if table_occurence[i - loop_i][j]["text"] != temp_head:
  1243. if cell.get("top_head_list"):
  1244. cell["top_head_list"] += [table_occurence[i - loop_i][j]["text"] + ":"]
  1245. else:
  1246. cell["top_head_list"] = [table_occurence[i - loop_i][j]["text"] + ":"]
  1247. top_head = table_occurence[i - loop_i][j]["text"] + ":" + top_head
  1248. head_row_col_list.append([i - loop_i, j])
  1249. else:
  1250. if cell.get("top_head_list"):
  1251. cell["top_head_list"] += [table_occurence[i - loop_i][j]["text"] + ":"]
  1252. else:
  1253. cell["top_head_list"] = [table_occurence[i - loop_i][j]["text"] + ":"]
  1254. top_head = table_occurence[i - loop_i][j]["text"] + ":" + top_head
  1255. head_row_col_list.append([i - loop_i, j])
  1256. find_flag = True
  1257. temp_head = table_occurence[i - loop_i][j]["text"]
  1258. table_occurence[i - loop_i][j]["occu_count"] += 1
  1259. else:
  1260. # 找到表头后遇到属性值就返回
  1261. if find_flag:
  1262. break
  1263. cell["top_head"] += top_head
  1264. if cell.get("top_head_row_index"):
  1265. cell["top_head_row_index"] += [x[0] for x in head_row_col_list]
  1266. else:
  1267. cell["top_head_row_index"] = [x[0] for x in head_row_col_list]
  1268. if cell.get("top_head_col_index"):
  1269. cell["top_head_col_index"] += [x[1] for x in head_row_col_list]
  1270. else:
  1271. cell["top_head_col_index"] = [x[1] for x in head_row_col_list]
  1272. find_flag = False
  1273. temp_head = ""
  1274. head_row_col_list = []
  1275. for loop_j in range(1, j + 1):
  1276. if not key_direct:
  1277. key_values = [1, 2]
  1278. else:
  1279. key_values = [2]
  1280. if table_occurence[i][j - loop_j]["type"] in key_values:
  1281. if find_flag:
  1282. if table_occurence[i][j - loop_j]["text"] != temp_head:
  1283. if cell.get("left_head_list"):
  1284. cell["left_head_list"] += [table_occurence[i][j - loop_j]["text"] + ":"]
  1285. else:
  1286. cell["left_head_list"] = [table_occurence[i][j - loop_j]["text"] + ":"]
  1287. left_head = table_occurence[i][j - loop_j]["text"] + ":" + left_head
  1288. head_row_col_list.append([i, j - loop_j])
  1289. else:
  1290. if cell.get("left_head_list"):
  1291. cell["left_head_list"] += [table_occurence[i][j - loop_j]["text"] + ":"]
  1292. else:
  1293. cell["left_head_list"] = [table_occurence[i][j - loop_j]["text"] + ":"]
  1294. left_head = table_occurence[i][j - loop_j]["text"] + ":" + left_head
  1295. head_row_col_list.append([i, j - loop_j])
  1296. find_flag = True
  1297. temp_head = table_occurence[i][j - loop_j]["text"]
  1298. table_occurence[i][j - loop_j]["occu_count"] += 1
  1299. else:
  1300. if find_flag:
  1301. break
  1302. cell["left_head"] += left_head
  1303. if cell.get("left_head_row_index"):
  1304. cell["left_head_row_index"] += [x[0] for x in head_row_col_list]
  1305. else:
  1306. cell["left_head_row_index"] = [x[0] for x in head_row_col_list]
  1307. if cell.get("left_head_col_index"):
  1308. cell["left_head_col_index"] += [x[1] for x in head_row_col_list]
  1309. else:
  1310. cell["left_head_col_index"] = [x[1] for x in head_row_col_list]
  1311. # 连接表头和属性值
  1312. if direct == "row":
  1313. for i in range(occu_height):
  1314. pack_text = ""
  1315. rank_text = ""
  1316. entity_text = ""
  1317. text_line = ""
  1318. money_text = ""
  1319. # 在同一句话中重复的可以去掉
  1320. text_set = set()
  1321. head = ""
  1322. last_text = ""
  1323. pack_text_location = []
  1324. rank_text_location = []
  1325. entity_text_location = []
  1326. text_line_location = []
  1327. money_text_location = []
  1328. for j in range(width):
  1329. cell = table_occurence[i][j]
  1330. if cell["type"] == 0 or (cell["type"] == 1 and cell["occu_count"] == 0):
  1331. cell = table_occurence[i][j]
  1332. head = (cell["top_head"] + ":") if len(cell["top_head"]) > 0 else ""
  1333. now_top_head = copy.deepcopy(head)
  1334. now_left_head = copy.deepcopy(cell["left_head"])
  1335. if re.search(
  1336. "[单报标限总]价|金额|成交报?价|报价|供应商|候选人|中标人|[利费]率|负责人|工期|服务(期限?|年限|时间|日期|周期)|("
  1337. "履约|履行)期限|合同(期限?|(完成|截止)(日期|时间))",
  1338. head):
  1339. head = cell["left_head"] + head
  1340. left_first = 1
  1341. else:
  1342. head += cell["left_head"]
  1343. left_first = 0
  1344. # print('len(text), len(sub_text), len(head)', cell["text"], len(text), len(sub_text), len(head))
  1345. # print('text111', text)
  1346. # print('pack_text, rank_text, entity_text, money_text, text_line', '1'+pack_text, '2'+rank_text, '3'+entity_text, '4'+money_text, '5'+text_line)
  1347. # print('head', head)
  1348. # print('sub_text111', sub_text)
  1349. if str(head + cell["text"]) in text_set:
  1350. cell['drop'] = 1
  1351. continue
  1352. if re.search(packPattern, head) is not None:
  1353. pack_text += head + cell["text"] + ","
  1354. pack_text_location += [[i, j, head + cell["text"] + ",", now_left_head, now_top_head, left_first]]
  1355. # 2020/11/23 大网站规则发现问题,if 改elif 20240620修复同时有排名及评标情况造成错误
  1356. elif re.search(rankPattern, head) is not None and re.search('(排名|排序|名次|顺序):?第?[\d一二三]', rank_text) is None:
  1357. # 排名替换为同一种表达
  1358. rank_text += head + cell["text"] + ","
  1359. rank_text_location += [[i, j, head + cell["text"] + ",", now_left_head, now_top_head, left_first]]
  1360. elif re.search(entityPattern, head) is not None:
  1361. entity_text += head + cell["text"] + ","
  1362. entity_text_location += [[i, j, head + cell["text"] + ",", now_left_head, now_top_head, left_first]]
  1363. else:
  1364. if re.search(moneyPattern, head) is not None and entity_text != "":
  1365. money_text += head + cell["text"] + ","
  1366. money_text_location += [[i, j, head + cell["text"] + ",", now_left_head, now_top_head, left_first]]
  1367. else:
  1368. text_line += head + cell["text"] + ","
  1369. text_line_location += [[i, j, head + cell["text"] + ",", now_left_head, now_top_head, left_first]]
  1370. text_set.add(str(head + cell["text"]))
  1371. last_text = cell['text']
  1372. # 计算key value在sentence的index
  1373. head_location_list = pack_text_location + rank_text_location + entity_text_location + text_line_location + money_text_location
  1374. current_loc = 0
  1375. for ii, jj, head_text, now_left_head, now_top_head, left_first in head_location_list:
  1376. cell = table_occurence[ii][jj]
  1377. # 左表头先于右表头
  1378. if left_first:
  1379. cell['left_head_sen_index'] = len(text) + current_loc
  1380. cell['top_head_sen_index'] = len(text) + current_loc + len(now_left_head)
  1381. else:
  1382. cell['left_head_sen_index'] = len(text) + current_loc + len(now_top_head)
  1383. cell['top_head_sen_index'] = len(text) + current_loc
  1384. cell['text_sen_index'] = len(text) + current_loc + len(now_left_head + now_top_head)
  1385. current_loc += len(head_text)
  1386. tr_text = pack_text + rank_text + entity_text + money_text + text_line
  1387. text += pack_text + rank_text + entity_text + money_text + text_line
  1388. # 修复367694716分两行表达
  1389. if len(text_set - set([' '])) == 1 and head == '' and len(last_text) < 25:
  1390. text = text if re.search('\w$', text[:-1]) else text[:-1]
  1391. # 修复494731937只有两行的,分句不合理
  1392. elif (width == 2 or len(text_set) == 1) and head != '' and len(tr_text) < 50:
  1393. text = text if re.search('\w$', text[:-1]) else text[:-1]
  1394. else:
  1395. text = text[:-1] + "。"
  1396. else:
  1397. for j in range(occu_width):
  1398. pack_text = ""
  1399. rank_text = ""
  1400. entity_text = ""
  1401. text_line = ""
  1402. text_set = set()
  1403. pack_text_location = []
  1404. rank_text_location = []
  1405. entity_text_location = []
  1406. text_line_location = []
  1407. money_text_location = []
  1408. for i in range(occu_height):
  1409. cell = table_occurence[i][j]
  1410. if cell["type"] == 0 or (cell["type"] == 1 and cell["occu_count"] == 0):
  1411. cell = table_occurence[i][j]
  1412. head = (cell["left_head"] + "") if len(cell["left_head"]) > 0 else ""
  1413. now_top_head = copy.deepcopy(cell["top_head"])
  1414. now_left_head = copy.deepcopy(head)
  1415. if re.search("[单报标限总]价|金额|成交报?价|报价|供应商|候选人|中标人|[利费]率|负责人|工期|服务(期限?|年限|时间|日期|周期)|(履约|履行)期限|合同(期限?|(完成|截止)(日期|时间))", head):
  1416. head = cell["top_head"] + head
  1417. left_first = 0
  1418. else:
  1419. head += cell["top_head"]
  1420. left_first = 1
  1421. if str(head + cell["text"]) in text_set:
  1422. cell['drop'] = 1
  1423. continue
  1424. if re.search(packPattern, head) is not None:
  1425. pack_text += head + cell["text"] + ","
  1426. pack_text_location += [[i, j, head + cell["text"] + ",", now_left_head, now_top_head, left_first]]
  1427. # 2020/11/23 大网站规则发现问题,if 改elif
  1428. elif re.search(rankPattern, head) is not None:
  1429. # 排名替换为同一种表达
  1430. rank_text += head + cell["text"] + ","
  1431. rank_text_location += [[i, j, head + cell["text"] + ",", now_left_head, now_top_head, left_first]]
  1432. # 2021/10/19 解决包含业绩的行调到前面问题
  1433. elif re.search(entityPattern, head) is not None and \
  1434. re.search('业绩|资格|条件', head) is None and re.search('业绩', cell["text"]) is None:
  1435. entity_text += head + cell["text"] + ","
  1436. entity_text_location += [[i, j, head + cell["text"] + ",", now_left_head, now_top_head, left_first]]
  1437. else:
  1438. text_line += head + cell["text"] + ","
  1439. text_line_location += [[i, j, head + cell["text"] + ",", now_left_head, now_top_head, left_first]]
  1440. text_set.add(str(head + cell["text"]))
  1441. # 计算key value在sentence的index
  1442. head_location_list = pack_text_location + rank_text_location + entity_text_location + text_line_location + money_text_location
  1443. current_loc = 0
  1444. for ii, jj, head_text, now_left_head, now_top_head, left_first in head_location_list:
  1445. cell = table_occurence[ii][jj]
  1446. # 左表头先于右表头
  1447. if left_first:
  1448. cell['left_head_sen_index'] = len(text) + current_loc
  1449. cell['top_head_sen_index'] = len(text) + current_loc + len(now_left_head)
  1450. else:
  1451. cell['left_head_sen_index'] = len(text) + current_loc + len(now_top_head)
  1452. cell['top_head_sen_index'] = len(text) + current_loc
  1453. cell['text_sen_index'] = len(text) + current_loc + len(now_left_head + now_top_head)
  1454. current_loc += len(head_text)
  1455. text += pack_text + rank_text + entity_text + text_line
  1456. text = text[:-1] + "。" if len(text) > 0 else text
  1457. all_table_occurence += table_occurence
  1458. return text, all_table_occurence
  1459. def process_dict(text, table):
  1460. kv_list = []
  1461. kv_dict_list = []
  1462. # print('text', len(text), text, ),
  1463. # print('table', table)
  1464. for r_index, row in enumerate(table):
  1465. for c_index, col in enumerate(row):
  1466. # print('col', col)
  1467. if col['type'] == 1:
  1468. continue
  1469. if col.get('drop'):
  1470. continue
  1471. if not col.get('left_head_list') and not col.get('top_head_list'):
  1472. _d = {
  1473. 'value': col['text'],
  1474. 'value_row_index': col['text_row_index'],
  1475. 'value_col_index': col['text_col_index'],
  1476. 'value_sen_index': col['text_sen_index'],
  1477. 'sen_value': text[col['text_sen_index']:col['text_sen_index'] + len(col['text'])],
  1478. }
  1479. kv_dict_list.append(_d)
  1480. continue
  1481. if col.get('text_sen_index') and col.get('text_sen_index') >= len(text):
  1482. # print('continue1')
  1483. continue
  1484. if col.get('left_head_list'):
  1485. # head, head_row_index, head_col_index 按文本顺序排序
  1486. zip_list = list(
  1487. zip(col.get('left_head_list'), col.get('left_head_row_index'), col.get('left_head_col_index')))
  1488. zip_list.sort(key=lambda x: (x[1], x[2]))
  1489. col['left_head_list'], col['left_head_row_index'], col['left_head_col_index'] = zip(*zip_list)
  1490. last_head = ""
  1491. for h_index, head in enumerate(col.get('left_head_list')):
  1492. _d = {
  1493. 'key': head,
  1494. 'value': col['text'],
  1495. 'key_row_index': col['left_head_row_index'][h_index],
  1496. 'key_col_index': col['left_head_col_index'][h_index],
  1497. 'key_sen_index': col['left_head_sen_index'] + len(last_head),
  1498. 'value_row_index': col['text_row_index'],
  1499. 'value_col_index': col['text_col_index'],
  1500. 'value_sen_index': col['text_sen_index'],
  1501. 'sen_key': text[
  1502. col['left_head_sen_index'] + len(last_head):col['left_head_sen_index'] + len(
  1503. last_head) + len(head)],
  1504. 'sen_value': text[col['text_sen_index']:col['text_sen_index'] + len(col['text'])],
  1505. }
  1506. kv_dict_list.append(_d)
  1507. last_head += head
  1508. if col.get('top_head_list'):
  1509. # head, head_row_index, head_col_index 按文本顺序排序
  1510. zip_list = list(
  1511. zip(col.get('top_head_list'), col.get('top_head_row_index'), col.get('top_head_col_index')))
  1512. zip_list.sort(key=lambda x: (x[1], x[2]))
  1513. col['top_head_list'], col['top_head_row_index'], col['top_head_col_index'] = zip(*zip_list)
  1514. last_head = ""
  1515. for h_index, head in enumerate(col.get('top_head_list')):
  1516. _d = {
  1517. 'key': head,
  1518. 'value': col['text'],
  1519. 'key_row_index': col['top_head_row_index'][h_index],
  1520. 'key_col_index': col['top_head_col_index'][h_index],
  1521. 'key_sen_index': col['top_head_sen_index'] + len(last_head),
  1522. 'value_row_index': col['text_row_index'],
  1523. 'value_col_index': col['text_col_index'],
  1524. 'value_sen_index': col['text_sen_index'],
  1525. 'sen_key': text[col['top_head_sen_index'] + len(last_head):col['top_head_sen_index'] + len(
  1526. last_head) + len(head)],
  1527. 'sen_value': text[col['text_sen_index']:col['text_sen_index'] + len(col['text'])],
  1528. }
  1529. kv_dict_list.append(_d)
  1530. last_head += head
  1531. return kv_list, kv_dict_list
  1532. def removeFix(inner_table,fix_value="~~"):
  1533. height = len(inner_table)
  1534. width = len(inner_table[0])
  1535. for h in range(height):
  1536. for w in range(width):
  1537. if inner_table[h][w][0]==fix_value:
  1538. inner_table[h][w][0] = ""
  1539. def trunTable(tbody,in_attachment):
  1540. # print(tbody.find('tbody'))
  1541. # 附件中的表格,排除异常错乱的表格
  1542. if in_attachment:
  1543. if tbody.name=='table':
  1544. _tbody = tbody.find('tbody')
  1545. if _tbody is None:
  1546. _tbody = tbody
  1547. else:
  1548. _tbody = tbody
  1549. _td_len_list = []
  1550. for _tr in _tbody.find_all(recursive=False):
  1551. len_td = len(_tr.find_all(recursive=False))
  1552. _td_len_list.append(len_td)
  1553. if _td_len_list:
  1554. if len(list(set(_td_len_list))) >= 8 or max(_td_len_list) > 100:
  1555. string_list = [re.sub("\s+","",i)for i in tbody.strings if i and i!='\n']
  1556. tbody.string = ",".join(string_list)
  1557. table_max_len = 30000
  1558. tbody.string = tbody.string[:table_max_len]
  1559. tbody.name = "turntable"
  1560. if return_kv:
  1561. return None, None, None
  1562. return None
  1563. # fixSpan(tbody)
  1564. # inner_table = getTable(tbody)
  1565. # inner_table = fixTable(inner_table)
  1566. table2list = TableTag2List()
  1567. return_html_table = True if return_kv else False
  1568. if return_html_table:
  1569. inner_table, html_table = table2list.table2list(tbody, segment, return_html_table,return_kv=return_kv)
  1570. inner_table = fixTable(inner_table)
  1571. html_table = fixTable(html_table, "")
  1572. else:
  1573. inner_table = table2list.table2list(tbody, segment,return_kv=return_kv)
  1574. inner_table = fixTable(inner_table)
  1575. if inner_table == []:
  1576. string_list = [re.sub("\s+", "", i) for i in tbody.strings if i and i != '\n']
  1577. tbody.string = ",".join(string_list)
  1578. table_max_len = 30000
  1579. tbody.string = tbody.string[:table_max_len]
  1580. # log('异常表格直接取全文')
  1581. tbody.name = "turntable"
  1582. if return_kv:
  1583. return None, None, None
  1584. return None
  1585. if len(inner_table)>0 and len(inner_table[0])>0:
  1586. for tr in inner_table:
  1587. for td in tr:
  1588. if isinstance(td, str):
  1589. tbody.string = segment(tbody,final=False)
  1590. table_max_len = 30000
  1591. tbody.string = tbody.string[:table_max_len]
  1592. # log('异常表格,不做表格处理,直接取全文')
  1593. tbody.name = "turntable"
  1594. if return_kv:
  1595. return None, None, None
  1596. return None
  1597. #inner_table,head_list = setHead_withRule(inner_table,pat_head,pat_value,3)
  1598. #inner_table,head_list = setHead_inline(inner_table)
  1599. # inner_table, head_list = setHead_initem(inner_table,pat_head)
  1600. inner_table, head_list = set_head_model(inner_table)
  1601. # inner_table,head_list = setHead_incontext(inner_table,pat_head)
  1602. # print("table_head", inner_table)
  1603. # print("head_list", head_list)
  1604. # for begin in range(len(head_list[:-1])):
  1605. # for item in inner_table[head_list[begin]:head_list[begin+1]]:
  1606. # print(item)
  1607. # print("====")
  1608. removeFix(inner_table)
  1609. # print("----")
  1610. # print(head_list)
  1611. # for item in inner_table:
  1612. # print(item)
  1613. # print('inner_table111', inner_table)
  1614. if return_kv:
  1615. text1, table = get_table_text_kv(inner_table, head_list)
  1616. tbody.string = text1
  1617. kv_list, kv_dict_list = process_dict(text1, table)
  1618. # html放入dict
  1619. for kv_dict in kv_dict_list:
  1620. html = html_table[kv_dict.get('value_row_index')][kv_dict.get('value_col_index')]
  1621. kv_dict['value_html'] = html
  1622. else:
  1623. tbody.string = getTableText(inner_table,head_list)
  1624. table_max_len = 30000
  1625. tbody.string = tbody.string[:table_max_len]
  1626. # print(tbody.string)
  1627. tbody.name = "turntable"
  1628. if return_kv:
  1629. return inner_table, kv_dict_list, text1
  1630. else:
  1631. return inner_table
  1632. if return_kv:
  1633. return None, None, None
  1634. return None
  1635. pat_head = re.compile('^(名称|序号|项目|标项|工程|品目[一二三四1234]|第[一二三四1234](标段|名|候选人|中标)|包段|标包|分包|包号|货物|单位|数量|价格|报价|金额|总价|单价|[招投中]标|候选|编号|得分|评委|评分|名次|排名|排序|科室|方式|工期|时间|产品|开始|结束|联系|日期|面积|姓名|证号|备注|级别|地[点址]|类型|代理|制造|企业资质|质量目标|工期目标|(需求|服务|项目|施工|采购|招租|出租|转让|出让|业主|询价|委托|权属|招标|竞得|抽取|承建)(人|方|单位)(名称)?|(供应商|供货商|服务商)(名称)?)$')
  1636. #pat_head = re.compile('(名称|序号|项目|工程|品目[一二三四1234]|第[一二三四1234](标段|候选人|中标)|包段|包号|货物|单位|数量|价格|报价|金额|总价|单价|[招投中]标|供应商|候选|编号|得分|评委|评分|名次|排名|排序|科室|方式|工期|时间|产品|开始|结束|联系|日期|面积|姓名|证号|备注|级别|地[点址]|类型|代理)')
  1637. pat_value = re.compile("(\d{2,}.\d{1}|\d+年\d+月|\d{8,}|\d{3,}-\d{6,}|有限[责任]*公司|^\d+$)")
  1638. list_innerTable = []
  1639. # 2022/2/9 删除干扰标签
  1640. for tag in soup.find_all('option'): #例子: 216661412
  1641. if 'selected' not in tag.attrs:
  1642. tag.extract()
  1643. for ul in soup.find_all('ul'): #例子 156439663 多个不同channel 类别的标题
  1644. if ul.find_all('li') == ul.findChildren(recursive=False) and len(set(re.findall(
  1645. '招标公告|中标结果公示|中标候选人公示|招标答疑|开标评标|合同履?约?公示|资格评审',
  1646. ul.get_text(), re.S)))>3:
  1647. ul.extract()
  1648. # tbodies = soup.find_all('table')
  1649. # 遍历表格中的每个tbody
  1650. tbodies = []
  1651. in_attachment = False
  1652. if soup.name=="table":
  1653. tbodies.append((soup,in_attachment))
  1654. for _part in soup.find_all():
  1655. if _part.name=='table':
  1656. tbodies.append((_part,in_attachment))
  1657. elif _part.name=='div':
  1658. if 'class' in _part.attrs and "richTextFetch" in _part['class']:
  1659. in_attachment = True
  1660. if return_kv and tbodies:
  1661. tbodies = tbodies[:1]
  1662. #逆序处理嵌套表格
  1663. # print('len(tbodies)1', len(tbodies))
  1664. # for tbody_index in range(1,len(tbodies)+1):
  1665. tbody_index = 1
  1666. while tbody_index < len(tbodies)+1:
  1667. tbody,_in_attachment = tbodies[len(tbodies)-tbody_index]
  1668. if len(tbody.find_all('tr')) == 1 and tbody_index > 0 and len(
  1669. tbodies[tbody_index - 1][0].find_all('tr')) == 1 and len(tbody.find_all(['th', 'td'])) == len(
  1670. tbodies[tbody_index - 1][0].find_all(['th', 'td'])): # 处理相邻表格都只有一行的情况;例:526321576
  1671. for row in tbody.find_all('tr'):
  1672. if tbodies[tbody_index - 1][0].tbody:
  1673. tbodies[tbody_index - 1][0].tbody.append(row)
  1674. else:
  1675. tbodies[tbody_index - 1][0].append(row)
  1676. inner_table = trunTable(tbodies[tbody_index - 1][0], _in_attachment)
  1677. if inner_table:
  1678. list_innerTable.append(inner_table)
  1679. tbody_index += 2
  1680. continue
  1681. inner_table = trunTable(tbody,_in_attachment)
  1682. list_innerTable.append(inner_table)
  1683. tbody_index += 1
  1684. # tbodies = soup.find_all('tbody')
  1685. # 遍历表格中的每个tbody
  1686. tbodies = []
  1687. in_attachment = False
  1688. if soup.name=="tbody":
  1689. tbodies.append((soup,in_attachment))
  1690. for _part in soup.find_all():
  1691. if _part.name == 'tbody':
  1692. tbodies.append((_part, in_attachment))
  1693. elif _part.name == 'div':
  1694. if 'class' in _part.attrs and "richTextFetch" in _part['class']:
  1695. in_attachment = True
  1696. if return_kv and tbodies:
  1697. tbodies = tbodies[:1]
  1698. #逆序处理嵌套表格
  1699. tbody_index = 1
  1700. # for tbody_index in range(1,len(tbodies)+1):
  1701. while tbody_index < len(tbodies) + 1:
  1702. tbody,_in_attachment = tbodies[len(tbodies)-tbody_index]
  1703. if len(tbody.find_all('tr')) == 1 and tbody_index > 0 and len(
  1704. tbodies[tbody_index - 1][0].find_all('tr')) == 1 and len(tbody.find_all(['th', 'td'])) == len(
  1705. tbodies[tbody_index - 1][0].find_all(['th', 'td'])): # 处理相邻表格都只有一行的情况;例:526321576
  1706. for row in tbody.find_all('tr'):
  1707. if tbodies[tbody_index - 1][0].tbody:
  1708. tbodies[tbody_index - 1][0].tbody.append(row)
  1709. else:
  1710. tbodies[tbody_index - 1][0].append(row)
  1711. inner_table = trunTable(tbodies[tbody_index - 1][0], _in_attachment)
  1712. if inner_table:
  1713. list_innerTable.append(inner_table)
  1714. tbody_index += 2
  1715. continue
  1716. inner_table = trunTable(tbody,_in_attachment)
  1717. list_innerTable.append(inner_table)
  1718. tbody_index += 1
  1719. if return_kv:
  1720. kv_list = []
  1721. for x in list_innerTable:
  1722. if x[1] is not None:
  1723. kv_list.extend(x[1])
  1724. text = ""
  1725. for x in list_innerTable:
  1726. if x[2] is not None:
  1727. text += x[2]
  1728. return soup, kv_list, text
  1729. return soup
  1730. # return list_innerTable
  1731. def table_head_repair_process(_inner_table, docid=None, show=0, show_row_index=0):
  1732. def pre_process(inner_table):
  1733. """
  1734. 修复前的预处理
  1735. """
  1736. # 循环处理单元格,一次获取需要的
  1737. for i in range(len(inner_table)):
  1738. for j in range(len(inner_table[i])):
  1739. # 删除前后逗号
  1740. inner_table[i][j][0] = re.sub('^[,, ]+', '', inner_table[i][j][0])
  1741. inner_table[i][j][0] = re.sub('[,, ]+$', '', inner_table[i][j][0])
  1742. inner_table[i][j][0] = re.sub('[, ]+', '', inner_table[i][j][0])
  1743. return inner_table
  1744. def repair_by_colon(inner_table):
  1745. """
  1746. 根据冒号修复当前格子的表头值
  1747. """
  1748. # 修复冒号在文本中间的,不能作为表头;(冒号后面需多个字)
  1749. # 冒号在括号中的除外
  1750. # 冒号在最后的,判断后一个格子是否有重复的文字
  1751. for i in range(len(inner_table)):
  1752. for j in range(len(inner_table[i])):
  1753. _text = inner_table[i][j][0]
  1754. if len(_text) >= 3 and inner_table[i][j][1] == 1:
  1755. match = re.search('[::]', _text)
  1756. if match:
  1757. start_index, end_index = match.span()
  1758. if start_index == 0:
  1759. continue
  1760. if end_index == len(_text):
  1761. if len(inner_table[i]) == 2 and j <= len(inner_table[i]) - 2 and inner_table[i][j+1][0] and (_text in inner_table[i][j+1][0] or inner_table[i][j+1][0] in _text):
  1762. inner_table[i][j][1] = 0
  1763. inner_table[i][j+1][1] = 0
  1764. else:
  1765. continue
  1766. if re.search('[((]', _text[:start_index]) and re.search('[))]', _text[end_index:]):
  1767. continue
  1768. m1 = re.search('[\u4e00-\u9fa50-9a-zA-Z]', _text[:start_index])
  1769. m2 = re.search('[\u4e00-\u9fa50-9a-zA-Z]', _text[end_index:])
  1770. if m1 and m2 and (len(m2.group()) >= 2 or m2.group() in ['是', '否']):
  1771. inner_table[i][j][1] = 0
  1772. return inner_table
  1773. def repair_by_duplicate(inner_table):
  1774. """
  1775. 根据列重复修复当前格子的表头值
  1776. """
  1777. # 统计每个值的表头情况
  1778. col_head_dict = {}
  1779. for i in range(len(inner_table)):
  1780. for j in range(len(inner_table[i])):
  1781. col = inner_table[i][j]
  1782. if col[0] in col_head_dict.keys():
  1783. col_head_dict[col[0]] += [col[1]]
  1784. else:
  1785. col_head_dict[col[0]] = [col[1]]
  1786. # 多个重复列的预测值不同,以第一个为准
  1787. for i in range(len(inner_table)):
  1788. col = inner_table[i][0]
  1789. key = col[0] + '\t' + str(0)
  1790. dup_dict = {}
  1791. for j in range(len(inner_table[i])):
  1792. if inner_table[i][j][0] == col[0]:
  1793. if key in dup_dict.keys():
  1794. dup_dict[key] += [j]
  1795. else:
  1796. dup_dict[key] = [j]
  1797. # if inner_table[i][j][1] != col[1]:
  1798. # if col != inner_table[i][0]:
  1799. # inner_table[i][j][1] = col[1]
  1800. # else:
  1801. # inner_table[i][0][1] = inner_table[i][j][1]
  1802. # col = inner_table[i][0]
  1803. else:
  1804. col = inner_table[i][j]
  1805. key = col[0] + '\t' + str(j)
  1806. dup_dict[key] = [j]
  1807. # print('dup_dict', dup_dict)
  1808. #
  1809. for key in dup_dict.keys():
  1810. index_list = dup_dict.get(key)
  1811. if len(index_list) <= 1:
  1812. continue
  1813. # 需要表头不同
  1814. table_head_list = []
  1815. for index in index_list:
  1816. table_head_list.append(inner_table[i][index][1])
  1817. table_head_list = list(set(table_head_list))
  1818. if len(table_head_list) <= 1:
  1819. continue
  1820. # 若是职业特殊处理
  1821. col = key.split('\t')[0]
  1822. if re.search('([^人]员|工程师|建造师|经理|安全负责人|技术负责人|合同商务负责人)$', col):
  1823. table_head_flag = 0
  1824. # 看是否包含表头
  1825. else:
  1826. table_head_flag = 0
  1827. for index in index_list:
  1828. if inner_table[i][index][1] == 1:
  1829. table_head_flag = 1
  1830. break
  1831. table_head = None
  1832. if index_list[0] > 0 and index_list[-1] == len(inner_table[i]) - 1:
  1833. table_head = inner_table[i][index_list[0]][1]
  1834. elif index_list[0] > 0 and index_list[-1] != len(inner_table[i]) - 1:
  1835. # 查看前面是否有表头-非表头表达
  1836. is_head_not_head = 0
  1837. for k in range(index_list[0]):
  1838. if k+1 < index_list[0] and inner_table[i][k][1] == 1 and inner_table[i][k+1][1] == 0:
  1839. is_head_not_head = 1
  1840. break
  1841. # 查看前后有没有表头
  1842. start_has_head = 0
  1843. end_has_head = 0
  1844. if not is_head_not_head:
  1845. for k in range(index_list[0], len(inner_table[i])):
  1846. if inner_table[i][k][0] == inner_table[i][index_list[0]][0]:
  1847. continue
  1848. if inner_table[i][k][1] == 1:
  1849. end_has_head = 1
  1850. break
  1851. for k in range(index_list[0]):
  1852. if inner_table[i][k][0] == inner_table[i][index_list[0]][0]:
  1853. continue
  1854. if inner_table[i][k][1] == 1:
  1855. start_has_head = 1
  1856. break
  1857. head_list = col_head_dict.get(inner_table[i][index_list[0]][0])
  1858. if is_head_not_head:
  1859. table_head = table_head_flag
  1860. elif len(head_list) >= 4:
  1861. if head_list.count(0) > head_list.count(1):
  1862. table_head = 0
  1863. else:
  1864. table_head = 1
  1865. elif not start_has_head and not end_has_head:
  1866. table_head = 0
  1867. else:
  1868. table_head = table_head_flag
  1869. elif index_list[0] == 0 and index_list[-1] == len(inner_table[i]) - 1:
  1870. table_head = table_head_flag
  1871. elif index_list[0] == 0 and index_list[-1] != len(inner_table[i]) - 1:
  1872. head_list = col_head_dict.get(inner_table[i][index_list[0]][0])
  1873. if len(head_list) >= 4:
  1874. if head_list.count(0) > head_list.count(1):
  1875. table_head = 0
  1876. else:
  1877. table_head = 1
  1878. else:
  1879. table_head = table_head_flag
  1880. if table_head is not None:
  1881. for index in index_list:
  1882. inner_table[i][index][1] = table_head
  1883. return inner_table
  1884. def repair_by_around(inner_table):
  1885. """
  1886. 根据周围的表头值修复当前格子的表头值
  1887. """
  1888. one_head_index_list = []
  1889. zero_head_index_list = []
  1890. all_head_index_list = []
  1891. one_not_head_index_list = []
  1892. no_dup_index_cnt_dict = {}
  1893. for i in range(len(inner_table)):
  1894. head_cnt = 0
  1895. head_index = None
  1896. head_dict = {}
  1897. for j in range(len(inner_table[i])):
  1898. # 统计表头数
  1899. if inner_table[i][j][1] == 1:
  1900. head_cnt += 1
  1901. head_index = j
  1902. if inner_table[i][j][0] not in ['~~', '', ' ']:
  1903. if inner_table[i][j][0] in head_dict.keys():
  1904. head_dict[inner_table[i][j][0]] += 1
  1905. else:
  1906. head_dict[inner_table[i][j][0]] = 1
  1907. no_dup_index_cnt_dict[i] = len(head_dict.keys())
  1908. # 表头数list
  1909. if head_cnt == 0:
  1910. zero_head_index_list.append(i)
  1911. elif head_cnt == 1:
  1912. # 这个单个表头需满足前面有非表头
  1913. find_flag = 0
  1914. for k in range(head_index):
  1915. if inner_table[i][k][1] == 0:
  1916. find_flag = 1
  1917. if find_flag and len(head_dict.keys()) > 2:
  1918. one_head_index_list.append(i)
  1919. elif head_cnt == len(inner_table[i]):
  1920. all_head_index_list.append(i)
  1921. elif head_cnt == len(inner_table[i]) - 1:
  1922. one_not_head_index_list.append(i)
  1923. # 第一行为表头,但有一个不为表头,下面行都非表头,表格行数小于4
  1924. if 0 in one_not_head_index_list and 1 in zero_head_index_list and len(inner_table) <= 4:
  1925. # 不相等的列值大于4
  1926. diff_col1 = []
  1927. for col in inner_table[0]:
  1928. if col[0] not in diff_col1 and len(col[0]) >= 1:
  1929. diff_col1.append(col[0])
  1930. diff_col2 = []
  1931. for col in inner_table[1]:
  1932. if col[0] not in diff_col2 and len(col[0]) >= 1:
  1933. diff_col2.append(col[0])
  1934. if len(diff_col1) >= 4 and len(diff_col2) >= 4:
  1935. for j in range(len(inner_table[0])):
  1936. inner_table[0][j][1] = 1
  1937. one_not_head_index_list.remove(0)
  1938. all_head_index_list.append(0)
  1939. # 一行很多列且都为表头,则剩下一个也为表头
  1940. for i in range(len(inner_table)):
  1941. if no_dup_index_cnt_dict.get(i) >= 5 and i in one_not_head_index_list:
  1942. for j in range(len(inner_table[i])):
  1943. inner_table[i][j][1] = 1
  1944. # 一行很多列且都不为表头,则剩下一个也不为表头,除了第一个
  1945. for i in range(len(inner_table)):
  1946. if no_dup_index_cnt_dict.get(i) >= 5 and i in one_head_index_list \
  1947. and inner_table[i][0][1] != 1 and inner_table[i][0][0] != '':
  1948. for j in range(len(inner_table[i])):
  1949. inner_table[i][j][1] = 0
  1950. # 一整个大表格,第一行为表头,下面行中有个别格子被识别为表头
  1951. # 候选人后面修复
  1952. for index in one_head_index_list:
  1953. if (index - 1 in zero_head_index_list and index - 2 in zero_head_index_list) \
  1954. or (index - 1 in zero_head_index_list and index - 2 in all_head_index_list) \
  1955. or (index - 1 in all_head_index_list):
  1956. for j in range(len(inner_table[index])):
  1957. inner_table[index][j][1] = 0
  1958. zero_head_index_list.append(index)
  1959. return inner_table
  1960. def repair_by_tenderer(inner_table):
  1961. """
  1962. 根据第一第二第三候选人修复当前格子的表头值
  1963. """
  1964. # 修复第一第二第三中标候选人作为表头
  1965. first_tenderer = ['第一中标候选人', '第一中标人', '第一中标(成交)人', '第一候选人']
  1966. second_tenderer = ['第二中标候选人', '第二中标(成交)候选人', '第二候选人']
  1967. third_tenderer = ['第三中标候选人', '第三中标(成交)候选人', '第三候选人']
  1968. # n1 next one, n2 next two, l1 last one, l2 last two
  1969. for i in range(len(inner_table)):
  1970. row = inner_table[i]
  1971. n1_row, n2_row = None, None
  1972. if i+1 < len(inner_table):
  1973. n1_row = inner_table[i+1]
  1974. if i+2 < len(inner_table):
  1975. n2_row = inner_table[i+2]
  1976. for j in range(len(row)):
  1977. row_col = row[j]
  1978. n1_row_col, n2_row_col = None, None
  1979. row_n1_col, row_n2_col = None, None
  1980. n1_row_n1_col, n2_row_n1_col, n1_row_n2_col = None, None, None
  1981. if n1_row:
  1982. n1_row_col = n1_row[j]
  1983. if n2_row:
  1984. n2_row_col = n2_row[j]
  1985. if j+1 < len(row):
  1986. row_n1_col = row[j+1]
  1987. if j+2 < len(row):
  1988. row_n2_col = row[j+2]
  1989. if n1_row and j+1 < len(n1_row):
  1990. n1_row_n1_col = n1_row[j+1]
  1991. if n2_row and j+1 < len(n2_row):
  1992. n2_row_n1_col = n2_row[j+1]
  1993. if n1_row and j+2 < len(n1_row):
  1994. n1_row_n2_col = n1_row[j+2]
  1995. # 连续作为行表头
  1996. if row_col[0] in first_tenderer and row_n1_col and row_n1_col[1] == 0:
  1997. if n1_row_col and n1_row_col[0] in second_tenderer and n1_row_n1_col and n1_row_n1_col[1] == 0:
  1998. inner_table[i][j][1] = 1
  1999. inner_table[i+1][j][1] = 1
  2000. if n2_row_col and n2_row_col[0] in third_tenderer and n2_row_n1_col and n2_row_n1_col[1] == 0:
  2001. inner_table[i+2][j][1] = 1
  2002. # 连续作为列表头
  2003. if row_col[0] in first_tenderer and n1_row_col and n1_row_col[1] == 0:
  2004. if row_n1_col and row_n1_col[0] in second_tenderer and n1_row_n1_col and n1_row_n1_col[1] == 0:
  2005. inner_table[i][j][1] = 1
  2006. inner_table[i][j+1][1] = 1
  2007. if row_n2_col and row_n2_col[0] in third_tenderer and n1_row_n2_col and n1_row_n2_col[1] == 0:
  2008. inner_table[i][j+2][1] = 1
  2009. return inner_table
  2010. def repair_by_keywords(inner_table):
  2011. """
  2012. 根据关键词修复当前格子的表头值
  2013. """
  2014. # 修复表头关键词未作为表头
  2015. # 末尾匹配匹配关键词且字数小于7,直接作为表头
  2016. head_keyword = ['供应商', '总价', '总价(元)', '总价\(元\)', '品目一', '品目二', '品目三']
  2017. # 末尾匹配关键词且前一列为表头且与前一列文本不同,直接不做表头
  2018. head_keyword2 = ['管理中心', '有限公司', '项目采购', '确定。', ]
  2019. # 开头匹配关键词,直接不做表头
  2020. head_keyword3 = ['详见', '选定', '咨询服务', '标准物资', '电汇', '承兑', '低档', '高档',
  2021. '更换配置', '各种数据']
  2022. # 文本匹配关键词且前一列为表头,直接作为表头
  2023. head_keyword4 = ['综合排名', '工期(交货期)', '检测批', '检测范围', '混凝土设计强检测批的容度等级',
  2024. '量(个)']
  2025. # 文本在关键词中,直接不做表头
  2026. head_keyword5 = ['殡葬用地', '电脑包', '电池']
  2027. # 文本匹配关键词,直接不作表头
  2028. head_keyword6 = ['市场行情', '有限公司', '能提供']
  2029. # 末尾匹配关键词,直接不做表头
  2030. head_keyword7 = ['基金', '结转', '结余', '税', '结余分配', '协议供货', '房屋',
  2031. '纳税人', '自然人', '计算所得额']
  2032. # 文本匹配关键词且整行都是表头,直接做表头
  2033. head_keyword8 = ['备注']
  2034. # n1 next one, n2 next two, l1 last one, l2 last two
  2035. for i in range(len(inner_table)):
  2036. row = inner_table[i]
  2037. for j in range(len(row)):
  2038. row_col = row[j]
  2039. row_l1_col = None
  2040. if j-1 >= 0:
  2041. row_l1_col = row[j-1]
  2042. for key in head_keyword:
  2043. match = re.search(key+'$', row_col[0])
  2044. if match and len(inner_table[i][j][0]) <= 6:
  2045. if show:
  2046. print('match head_keyword')
  2047. inner_table[i][j][1] = 1
  2048. for key in head_keyword2:
  2049. match = re.search(key+'$', row_col[0])
  2050. if j > 0 and row_l1_col and row_l1_col[1] == 1 and row_l1_col[0] != row_col[0] and match and row_col[1] == 1:
  2051. if show:
  2052. print('match head_keyword2')
  2053. inner_table[i][j][1] = 0
  2054. for key in head_keyword3:
  2055. match = re.search('^'+key, row_col[0])
  2056. if match and row_col[1] == 1:
  2057. if show:
  2058. print('match head_keyword3')
  2059. inner_table[i][j][1] = 0
  2060. for key in head_keyword4:
  2061. match = re.search(key, row_col[0])
  2062. if j > 0 and row_l1_col and row_l1_col[1] == 1 and match and row_col[1] == 0:
  2063. if show:
  2064. print('match head_keyword4')
  2065. inner_table[i][j][1] = 1
  2066. if row_col[0] in head_keyword5:
  2067. if show:
  2068. print('match head_keyword5')
  2069. inner_table[i][j][1] = 0
  2070. for key in head_keyword6:
  2071. match = re.search(key, row_col[0])
  2072. if match:
  2073. if show:
  2074. print('match head_keyword6')
  2075. inner_table[i][j][1] = 0
  2076. for key in head_keyword7:
  2077. match = re.search(key+'$', row_col[0])
  2078. if match and row_col[1] == 1:
  2079. if show:
  2080. print('match head_keyword7')
  2081. inner_table[i][j][1] = 0
  2082. if row_col[0] in head_keyword8 and row_col[1] == 0:
  2083. if show:
  2084. print('match head_keyword8')
  2085. all_head_flag = 1
  2086. for k in range(len(row)):
  2087. if row[k][0] in ['', row_col[0]]:
  2088. continue
  2089. if row[k][1] == 0:
  2090. print('row[k]', row[k])
  2091. all_head_flag = 0
  2092. break
  2093. # print('all_head_flag', all_head_flag)
  2094. if all_head_flag:
  2095. inner_table[i][j][1] = 1
  2096. return inner_table
  2097. def repair_by_length(inner_table):
  2098. for i in range(len(inner_table)):
  2099. for j in range(len(inner_table[i])):
  2100. if len(inner_table[i][j][0]) >= 30:
  2101. inner_table[i][j][1] = 0
  2102. return inner_table
  2103. def repair_by_summation(inner_table):
  2104. # 修复合计在中间的特殊情况
  2105. if len(inner_table) >= 3 and len(inner_table[1]) == 2 \
  2106. and inner_table[1][0][0] == '合计' and inner_table[1][1][0].endswith('%'):
  2107. inner_table[1][0][1] = 0
  2108. inner_table[1][1][1] = 0
  2109. return inner_table
  2110. def repair_by_rank(inner_table):
  2111. if not inner_table or (inner_table and len(inner_table[0]) < 3):
  2112. return inner_table
  2113. for i in range(len(inner_table)):
  2114. for j in range(len(inner_table[i])-2):
  2115. if inner_table[i][j][0] in ['第一名'] and inner_table[i][j+1][0] in ['第二名'] and inner_table[i][j+2][0] in ['第三名']:
  2116. inner_table[i][j][1] = 1
  2117. inner_table[i][j+1][1] = 1
  2118. inner_table[i][j+2][1] = 1
  2119. return inner_table
  2120. _inner_table = pre_process(_inner_table)
  2121. compare_inner_table = copy.deepcopy(_inner_table)
  2122. if show:
  2123. print('table_head_repair_process1', show_row_index, _inner_table[show_row_index])
  2124. _inner_table = repair_by_rank(_inner_table)
  2125. if _inner_table != compare_inner_table:
  2126. compare_inner_table = copy.deepcopy(_inner_table)
  2127. log('table_head repair1.5 ' + str(docid))
  2128. if show:
  2129. print('table_head_repair_process1.5', show_row_index, _inner_table[show_row_index])
  2130. _inner_table = repair_by_colon(_inner_table)
  2131. if _inner_table != compare_inner_table:
  2132. compare_inner_table = copy.deepcopy(_inner_table)
  2133. log('table_head repair2 ' + str(docid))
  2134. if show:
  2135. print('table_head_repair_process2', show_row_index, _inner_table[show_row_index])
  2136. _inner_table = repair_by_keywords(_inner_table)
  2137. if _inner_table != compare_inner_table:
  2138. compare_inner_table = copy.deepcopy(_inner_table)
  2139. log('table_head repair3 ' + str(docid))
  2140. if show:
  2141. print('table_head_repair_process3', show_row_index, _inner_table[show_row_index])
  2142. _inner_table = repair_by_tenderer(_inner_table)
  2143. if _inner_table != compare_inner_table:
  2144. compare_inner_table = copy.deepcopy(_inner_table)
  2145. log('table_head repair4 ' + str(docid))
  2146. if show:
  2147. print('table_head_repair_process4', show_row_index, _inner_table[show_row_index])
  2148. _inner_table = repair_by_duplicate(_inner_table)
  2149. if _inner_table != compare_inner_table:
  2150. compare_inner_table = copy.deepcopy(_inner_table)
  2151. log('table_head repair5 ' + str(docid))
  2152. if show:
  2153. print('table_head_repair_process5', show_row_index, _inner_table[show_row_index])
  2154. _inner_table = repair_by_around(_inner_table)
  2155. if _inner_table != compare_inner_table:
  2156. compare_inner_table = copy.deepcopy(_inner_table)
  2157. log('table_head repair6 ' + str(docid))
  2158. if show:
  2159. print('table_head_repair_process6', show_row_index, _inner_table[show_row_index])
  2160. _inner_table = repair_by_tenderer(_inner_table)
  2161. if _inner_table != compare_inner_table:
  2162. compare_inner_table = copy.deepcopy(_inner_table)
  2163. log('table_head repair7 ' + str(docid))
  2164. if show:
  2165. print('table_head_repair_process7', show_row_index, _inner_table[show_row_index])
  2166. _inner_table = repair_by_keywords(_inner_table)
  2167. if _inner_table != compare_inner_table:
  2168. compare_inner_table = copy.deepcopy(_inner_table)
  2169. log('table_head repair8 ' + str(docid))
  2170. if show:
  2171. print('table_head_repair_process8', show_row_index, _inner_table[show_row_index])
  2172. _inner_table = repair_by_length(_inner_table)
  2173. if _inner_table != compare_inner_table:
  2174. compare_inner_table = copy.deepcopy(_inner_table)
  2175. print('table_head repair9 ' + str(docid))
  2176. if show:
  2177. print('table_head_repair_process9', show_row_index, _inner_table[show_row_index])
  2178. _inner_table = repair_by_summation(_inner_table)
  2179. if show:
  2180. print('table_head_repair_process10', show_row_index, _inner_table[show_row_index])
  2181. return _inner_table
  2182. re_num = re.compile("[二三四五六七八九]十[一二三四五六七八九]?|十[一二三四五六七八九]|[一二三四五六七八九十]")
  2183. num_dict = {
  2184. "一": 1, "二": 2,
  2185. "三": 3, "四": 4,
  2186. "五": 5, "六": 6,
  2187. "七": 7, "八": 8,
  2188. "九": 9, "十": 10}
  2189. # 一百以内的中文大写转换为数字
  2190. def change2num(text):
  2191. result_num = -1
  2192. # text = text[:6]
  2193. match = re_num.search(text)
  2194. if match:
  2195. _num = match.group()
  2196. if num_dict.get(_num):
  2197. return num_dict.get(_num)
  2198. else:
  2199. tenths = 1
  2200. the_unit = 0
  2201. num_split = _num.split("十")
  2202. if num_dict.get(num_split[0]):
  2203. tenths = num_dict.get(num_split[0])
  2204. if num_dict.get(num_split[1]):
  2205. the_unit = num_dict.get(num_split[1])
  2206. result_num = tenths * 10 + the_unit
  2207. elif re.search("\d{1,2}",text):
  2208. _num = re.search("\d{1,2}",text).group()
  2209. result_num = int(_num)
  2210. return result_num
  2211. #大纲分段处理
  2212. def get_preprocessed_outline(soup):
  2213. pattern_0 = re.compile("^(?:[二三四五六七八九]十[一二三四五六七八九]?|十[一二三四五六七八九]|[一二三四五六七八九十])[、.\.]")
  2214. pattern_1 = re.compile("^[\((]?(?:[二三四五六七八九]十[一二三四五六七八九]?|十[一二三四五六七八九]|[一二三四五六七八九十])[\))]")
  2215. pattern_2 = re.compile("^\d{1,2}[、.\.](?=[^\d]{1,2}|$)")
  2216. pattern_3 = re.compile("^[\((]?\d{1,2}[\))]")
  2217. pattern_list = [pattern_0, pattern_1, pattern_2, pattern_3]
  2218. body = soup.find("body")
  2219. if body == None:
  2220. return soup # 修复 无body的报错 例子:264419050
  2221. body_child = body.find_all(recursive=False)
  2222. deal_part = body
  2223. # print(body_child[0]['id'])
  2224. if 'id' in body_child[0].attrs:
  2225. if len(body_child) <= 2 and body_child[0]['id'] == 'pcontent':
  2226. deal_part = body_child[0]
  2227. if len(deal_part.find_all(recursive=False))>2:
  2228. deal_part = deal_part.parent
  2229. skip_tag = ['turntable', 'tbody', 'th', 'tr', 'td', 'table','thead','tfoot']
  2230. for part in deal_part.find_all(recursive=False):
  2231. # 查找解析文本的主干部分
  2232. is_main_text = False
  2233. through_text_num = 0
  2234. while (not is_main_text and part.find_all(recursive=False)):
  2235. while len(part.find_all(recursive=False)) == 1 and part.get_text(strip=True) == \
  2236. part.find_all(recursive=False)[0].get_text(strip=True):
  2237. part = part.find_all(recursive=False)[0]
  2238. max_len = len(part.get_text(strip=True))
  2239. is_main_text = True
  2240. for t_part in part.find_all(recursive=False):
  2241. if t_part.name not in skip_tag and t_part.get_text(strip=True)!="":
  2242. through_text_num += 1
  2243. if t_part.get_text(strip=True)!="" and len(t_part.get_text(strip=True))/max_len>=0.65:
  2244. if t_part.name not in skip_tag:
  2245. is_main_text = False
  2246. part = t_part
  2247. break
  2248. else:
  2249. while len(t_part.find_all(recursive=False)) == 1 and t_part.get_text(strip=True) == \
  2250. t_part.find_all(recursive=False)[0].get_text(strip=True):
  2251. t_part = t_part.find_all(recursive=False)[0]
  2252. if through_text_num>2:
  2253. is_table = True
  2254. for _t_part in t_part.find_all(recursive=False):
  2255. if _t_part.name not in skip_tag:
  2256. is_table = False
  2257. break
  2258. if not is_table:
  2259. is_main_text = False
  2260. part = t_part
  2261. break
  2262. else:
  2263. is_main_text = False
  2264. part = t_part
  2265. break
  2266. is_find = False
  2267. for _pattern in pattern_list:
  2268. last_index = 0
  2269. handle_list = []
  2270. for _part in part.find_all(recursive=False):
  2271. if _part.name not in skip_tag and _part.get_text(strip=True) != "":
  2272. # print('text:', _part.get_text(strip=True))
  2273. re_match = re.search(_pattern, _part.get_text(strip=True))
  2274. if re_match:
  2275. outline_index = change2num(re_match.group())
  2276. if last_index < outline_index:
  2277. # _part.insert_before("##split##")
  2278. handle_list.append(_part)
  2279. last_index = outline_index
  2280. if len(handle_list)>1:
  2281. is_find = True
  2282. for _part in handle_list:
  2283. _part.insert_before("##split##")
  2284. if is_find:
  2285. break
  2286. # print(soup)
  2287. return soup
  2288. #数据清洗
  2289. def segment(soup,final=True):
  2290. # print("==")
  2291. # print(soup)
  2292. # print("====")
  2293. #segList = ["tr","div","h1", "h2", "h3", "h4", "h5", "h6", "header"]
  2294. subspaceList = ["td",'a',"span","p"]
  2295. if soup.name in subspaceList:
  2296. #判断有值叶子节点数
  2297. _count = 0
  2298. for child in soup.find_all(recursive=True):
  2299. if child.get_text().strip()!="" and len(child.find_all())==0:
  2300. _count += 1
  2301. if _count<=1:
  2302. text = soup.get_text()
  2303. # 2020/11/24 大网站规则添加
  2304. if 'title' in soup.attrs:
  2305. if '...' in soup.get_text() and soup.get_text().strip()[:-3] in soup.attrs['title']:
  2306. text = soup.attrs['title']
  2307. _list = []
  2308. for x in re.split("\s+",text):
  2309. if x.strip()!="":
  2310. _list.append(len(x))
  2311. if len(_list)>0:
  2312. _minLength = min(_list)
  2313. if _minLength>2:
  2314. _substr = ","
  2315. else:
  2316. _substr = ""
  2317. else:
  2318. _substr = ""
  2319. text = text.replace("\r\n",",").replace("\n",",")
  2320. text = re.sub("\s+",_substr,text)
  2321. # text = re.sub("\s+","##space##",text)
  2322. return text
  2323. segList = ["title"]
  2324. commaList = ["div","br","td","p","li","h1","h2","h3","h4","h5","h6"]
  2325. #commaList = []
  2326. spaceList = ["span"]
  2327. tbodies = soup.find_all('tbody')
  2328. if len(tbodies) == 0:
  2329. tbodies = soup.find_all('table')
  2330. # 递归遍历所有节点,插入符号
  2331. for child in soup.find_all(recursive=True):
  2332. # print(child.name,child.get_text())
  2333. if child.name in segList:
  2334. child.insert_after("。")
  2335. if child.name in commaList:
  2336. child.insert_after(",")
  2337. # if child.name != "td" and re.match('[((][一二三四五六七八九十]+[))]|[一二三四五六七八九十]+\s*、', child.get_text().strip()): # 大纲前面用句号分割 20240930 注销,修复529501491关键词 三、中标供应商:(一)单位名称被分句
  2338. # child.insert_before("。")
  2339. # if child.name == 'div' and 'class' in child.attrs:
  2340. # # 添加附件"attachment"标识
  2341. # if "richTextFetch" in child['class']:
  2342. # child.insert_before("##attachment##")
  2343. # print(child.parent)
  2344. # if child.name in subspaceList:
  2345. # child.insert_before("#subs"+str(child.name)+"#")
  2346. # child.insert_after("#sube"+str(child.name)+"#")
  2347. # if child.name in spaceList:
  2348. # child.insert_after(" ")
  2349. text = str(soup.get_text())
  2350. #替换英文冒号为中文冒号
  2351. text = re.sub("(?<=[\u4e00-\u9fa5]):|:(?=[\u4e00-\u9fa5])",":",text)
  2352. #替换为中文逗号
  2353. text = re.sub("(?<=[\u4e00-\u9fa5]),|,(?=[\u4e00-\u9fa5])",",",text)
  2354. #替换为中文分号
  2355. text = re.sub("(?<=[\u4e00-\u9fa5]);|;(?=[\u4e00-\u9fa5])",";",text)
  2356. # 感叹号替换为中文句号
  2357. text = re.sub("(?<=[\u4e00-\u9fa5])[!!]|[!!](?=[\u4e00-\u9fa5])","。",text)
  2358. #替换格式未识别的问号为" " ,update:2021/7/20
  2359. text = re.sub("[?\?]{2,}|\n"," ",text)
  2360. #替换"""为"“",否则导入deepdive出错
  2361. # text = text.replace('"',"“").replace("\r","").replace("\n",",")
  2362. text = text.replace('"',"“").replace("\r","").replace("\n","").replace("\\n","") #2022/1/4修复 非分段\n 替换为逗号造成 公司拆分 span \n南航\n上海\n分公司
  2363. text = re.sub("(&nbsp)+"," ",text) # 空白符替换
  2364. # print('==1',text)
  2365. # text = re.sub("\s{4,}",",",text)
  2366. # 解决公告中的" "空格替换问题
  2367. if re.search("\s{4,}",text):
  2368. _text = ""
  2369. for _sent in re.split("。+",text):
  2370. for _sent2 in re.split(',+',_sent):
  2371. for _sent3 in re.split(":+",_sent2):
  2372. pre_t = ''
  2373. for _t in re.split("\s{4,}",_sent3):
  2374. if len(_t)<3 or len(pre_t)<3 or re.search('[^\w\s]$', pre_t): # 20240726 前文小于3字或以符合结尾的不加 避免乱加逗号 例:2) 申请人的资格要求
  2375. _text += _t
  2376. else:
  2377. _text += ","+_t
  2378. pre_t = _t
  2379. _text += ":"
  2380. _text = _text[:-1]
  2381. _text += ","
  2382. _text = _text[:-1]
  2383. _text += "。"
  2384. _text = _text[:-1]
  2385. text = _text
  2386. # print('==2',text)
  2387. #替换标点
  2388. #替换连续的标点
  2389. if final:
  2390. text = re.sub("##space##"," ",text)
  2391. punc_pattern = "(?P<del>[。,;::,\s]+)"
  2392. list_punc = re.findall(punc_pattern,text)
  2393. list_punc.sort(key=lambda x:len(x),reverse=True)
  2394. for punc_del in list_punc:
  2395. if len(punc_del)>1:
  2396. if len(punc_del.strip())>0:
  2397. if ":" in punc_del.strip():
  2398. if "。" in punc_del.strip():
  2399. text = re.sub(punc_del, ":。", text)
  2400. else:
  2401. text = re.sub(punc_del,":",text)
  2402. else:
  2403. text = re.sub(punc_del,punc_del.strip()[0],text) #2021/12/09 修正由于某些标签后插入符号把原来符号替换
  2404. else:
  2405. text = re.sub(punc_del," ",text) # 多个空字符替换为一个空格(防止时间类连接),后面还有对空格处理
  2406. #将连续的中文句号替换为一个
  2407. # text_split = text.split("。")
  2408. # text_split = [x for x in text_split if len(x)>0]
  2409. # text = "。".join(text_split)
  2410. text = re.sub('。+', '。', text).lstrip('。') # 20240703 修复上面的方法造成文末句号丢失问题。
  2411. # #删除标签中的所有空格
  2412. # for subs in subspaceList:
  2413. # patten = "#subs"+str(subs)+"#(.*?)#sube"+str(subs)+"#"
  2414. # while(True):
  2415. # oneMatch = re.search(re.compile(patten),text)
  2416. # if oneMatch is not None:
  2417. # _match = oneMatch.group(1)
  2418. # text = text.replace("#subs"+str(subs)+"#"+_match+"#sube"+str(subs)+"#",_match)
  2419. # else:
  2420. # break
  2421. # text过大报错
  2422. LOOP_LEN = 10000
  2423. LOOP_BEGIN = 0
  2424. _text = ""
  2425. if len(text)<10000000:
  2426. while(LOOP_BEGIN<len(text)):
  2427. _text += re.sub(")",")",re.sub("(","(",re.sub("\s(?!\d{1,2}[::]\d{2}|\d{1,2}[点时])","",text[LOOP_BEGIN:LOOP_BEGIN+LOOP_LEN])))
  2428. LOOP_BEGIN += LOOP_LEN
  2429. text = _text
  2430. # 附件标识前修改为句号,避免正文和附件内容混合在一起
  2431. text = re.sub("[^。](?=##attachment##)","。",text)
  2432. text = re.sub("[^。](?=##attachment_begin##)","。",text)
  2433. text = re.sub("[^。](?=##attachment_end##)","。",text)
  2434. text = re.sub("##attachment_begin##。","##attachment_begin##",text)
  2435. text = re.sub("##attachment_end##。","##attachment_end##",text)
  2436. return text
  2437. '''
  2438. #数据清洗
  2439. def segment(soup):
  2440. segList = ["title"]
  2441. commaList = ["p","div","h1", "h2", "h3", "h4", "h5", "h6", "header", "dl", "ul", "label"]
  2442. spaceList = ["span"]
  2443. tbodies = soup.find_all('tbody')
  2444. if len(tbodies) == 0:
  2445. tbodies = soup.find_all('table')
  2446. # 递归遍历所有节点,插入符号
  2447. for child in soup.find_all(recursive=True):
  2448. if child.name == 'br':
  2449. child.insert_before(',')
  2450. child_text = re.sub('\s', '', child.get_text())
  2451. if child_text == '' or child_text[-1] in ['。',',',':',';']:
  2452. continue
  2453. if child.name in segList:
  2454. child.insert_after("。")
  2455. if child.name in commaList:
  2456. if len(child_text)>3 and len(child_text) <50: # 先判断是否字数少于50,成立加逗号,否则加句号
  2457. child.insert_after(",")
  2458. elif len(child_text) >=50:
  2459. child.insert_after("。")
  2460. #if child.name in spaceList:
  2461. #child.insert_after(" ")
  2462. text = str(soup.get_text())
  2463. text = re.sub("\s{5,}",",",text)
  2464. text = text.replace('"',"“").replace("\r","").replace("\n",",")
  2465. #替换"""为"“",否则导入deepdive出错
  2466. text = text.replace('"',"“")
  2467. #text = text.replace('"',"“").replace("\r","").replace("\n","")
  2468. #删除所有空格
  2469. text = re.sub("\s+","#nbsp#",text)
  2470. text_list = text.split('#nbsp#')
  2471. new_text = ''
  2472. for i in range(len(text_list)-1):
  2473. if text_list[i] == '' or text_list[i][-1] in [',','。',';',':']:
  2474. new_text += text_list[i]
  2475. elif re.findall('([一二三四五六七八九]、)', text_list[i+1][:4]) != []:
  2476. new_text += text_list[i] + '。'
  2477. elif re.findall('([0-9]、)', text_list[i+1][:4]) != []:
  2478. new_text += text_list[i] + ';'
  2479. elif text_list[i].isdigit() and text_list[i+1].isdigit():
  2480. new_text += text_list[i] + ' '
  2481. elif text_list[i][-1] in ['-',':','(',')','/','(',')','——','年','月','日','时','分','¥'] or text_list[i+1][0] in ['-',':','(',')','/','(',')','——','年','月','日','时','分','元','万元']:
  2482. new_text += text_list[i]
  2483. elif len(text_list[i]) >= 3 and len(text_list[i+1]) >= 3:
  2484. new_text += text_list[i] + ','
  2485. else:
  2486. new_text += text_list[i]
  2487. new_text += text_list[-1]
  2488. text = new_text
  2489. #替换英文冒号为中文冒号
  2490. text = re.sub("(?<=[\u4e00-\u9fa5]):|:(?=[\u4e00-\u9fa5])",":",text)
  2491. #替换为中文逗号
  2492. text = re.sub("(?<=[\u4e00-\u9fa5]),|,(?=[\u4e00-\u9fa5])",",",text)
  2493. #替换为中文分号
  2494. text = re.sub("(?<=[\u4e00-\u9fa5]);|;(?=[\u4e00-\u9fa5])",";",text)
  2495. #替换标点
  2496. while(True):
  2497. #替换连续的标点
  2498. punc = re.search(",(?P<punc>:|。|,|;)\s*",text)
  2499. if punc is not None:
  2500. text = re.sub(","+punc.group("punc")+"\s*",punc.group("punc"),text)
  2501. punc = re.search("(?P<punc>:|。|,|;)\s*,",text)
  2502. if punc is not None:
  2503. text = re.sub(punc.group("punc")+"\s*,",punc.group("punc"),text)
  2504. else:
  2505. #替换标点之后的空格
  2506. punc = re.search("(?P<punc>:|。|,|;)\s+",text)
  2507. if punc is not None:
  2508. text = re.sub(punc.group("punc")+"\s+",punc.group("punc"),text)
  2509. else:
  2510. break
  2511. #将连续的中文句号替换为一个
  2512. text_split = text.split("。")
  2513. text_split = [x for x in text_split if len(x)>0]
  2514. text = "。".join(text_split)
  2515. #替换中文括号为英文括号
  2516. text = re.sub("(","(",text)
  2517. text = re.sub(")",")",text)
  2518. return text
  2519. '''
  2520. #连续实体合并(弃用)
  2521. def union_ner(list_ner):
  2522. result_list = []
  2523. union_index = []
  2524. union_index_set = set()
  2525. for i in range(len(list_ner)-1):
  2526. if len(set([str(list_ner[i][2]),str(list_ner[i+1][2])])&set(["org","company"]))==2:
  2527. if list_ner[i][1]-list_ner[i+1][0]==1:
  2528. union_index_set.add(i)
  2529. union_index_set.add(i+1)
  2530. union_index.append((i,i+1))
  2531. for i in range(len(list_ner)):
  2532. if i not in union_index_set:
  2533. result_list.append(list_ner[i])
  2534. for item in union_index:
  2535. #print(str(list_ner[item[0]][3])+str(list_ner[item[1]][3]))
  2536. 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])))
  2537. return result_list
  2538. # def get_preprocessed(articles,useselffool=False):
  2539. # '''
  2540. # @summary:预处理步骤,NLP处理、实体识别
  2541. # @param:
  2542. # articles:待处理的文章list [[id,source,jointime,doc_id,title]]
  2543. # @return:list of articles,list of each article of sentences,list of each article of entitys
  2544. # '''
  2545. # list_articles = []
  2546. # list_sentences = []
  2547. # list_entitys = []
  2548. # cost_time = dict()
  2549. # for article in articles:
  2550. # list_sentences_temp = []
  2551. # list_entitys_temp = []
  2552. # doc_id = article[0]
  2553. # sourceContent = article[1]
  2554. # _send_doc_id = article[3]
  2555. # _title = article[4]
  2556. # #表格处理
  2557. # key_preprocess = "tableToText"
  2558. # start_time = time.time()
  2559. # article_processed = segment(tableToText(BeautifulSoup(sourceContent,"lxml")))
  2560. #
  2561. # # log(article_processed)
  2562. #
  2563. # if key_preprocess not in cost_time:
  2564. # cost_time[key_preprocess] = 0
  2565. # cost_time[key_preprocess] += time.time()-start_time
  2566. #
  2567. # #article_processed = article[1]
  2568. # list_articles.append(Article(doc_id,article_processed,sourceContent,_send_doc_id,_title))
  2569. # #nlp处理
  2570. # if article_processed is not None and len(article_processed)!=0:
  2571. # split_patten = "。"
  2572. # sentences = []
  2573. # _begin = 0
  2574. # for _iter in re.finditer(split_patten,article_processed):
  2575. # sentences.append(article_processed[_begin:_iter.span()[1]])
  2576. # _begin = _iter.span()[1]
  2577. # sentences.append(article_processed[_begin:])
  2578. #
  2579. # lemmas = []
  2580. # doc_offsets = []
  2581. # dep_types = []
  2582. # dep_tokens = []
  2583. #
  2584. # time1 = time.time()
  2585. #
  2586. # '''
  2587. # tokens_all = fool.cut(sentences)
  2588. # #pos_all = fool.LEXICAL_ANALYSER.pos(tokens_all)
  2589. # #ner_tag_all = fool.LEXICAL_ANALYSER.ner_labels(sentences,tokens_all)
  2590. # ner_entitys_all = fool.ner(sentences)
  2591. # '''
  2592. # #限流执行
  2593. # key_nerToken = "nerToken"
  2594. # start_time = time.time()
  2595. # tokens_all,ner_entitys_all = getTokensAndNers(sentences,useselffool=useselffool)
  2596. # if key_nerToken not in cost_time:
  2597. # cost_time[key_nerToken] = 0
  2598. # cost_time[key_nerToken] += time.time()-start_time
  2599. #
  2600. #
  2601. # for sentence_index in range(len(sentences)):
  2602. #
  2603. #
  2604. #
  2605. # list_sentence_entitys = []
  2606. # sentence_text = sentences[sentence_index]
  2607. # tokens = tokens_all[sentence_index]
  2608. #
  2609. # list_tokenbegin = []
  2610. # begin = 0
  2611. # for i in range(0,len(tokens)):
  2612. # list_tokenbegin.append(begin)
  2613. # begin += len(str(tokens[i]))
  2614. # list_tokenbegin.append(begin+1)
  2615. # #pos_tag = pos_all[sentence_index]
  2616. # pos_tag = ""
  2617. #
  2618. # ner_entitys = ner_entitys_all[sentence_index]
  2619. #
  2620. # 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))
  2621. #
  2622. # #识别package
  2623. #
  2624. #
  2625. # #识别实体
  2626. # for ner_entity in ner_entitys:
  2627. # begin_index_temp = ner_entity[0]
  2628. # end_index_temp = ner_entity[1]
  2629. # entity_type = ner_entity[2]
  2630. # entity_text = ner_entity[3]
  2631. #
  2632. # for j in range(len(list_tokenbegin)):
  2633. # if list_tokenbegin[j]==begin_index_temp:
  2634. # begin_index = j
  2635. # break
  2636. # elif list_tokenbegin[j]>begin_index_temp:
  2637. # begin_index = j-1
  2638. # break
  2639. # begin_index_temp += len(str(entity_text))
  2640. # for j in range(begin_index,len(list_tokenbegin)):
  2641. # if list_tokenbegin[j]>=begin_index_temp:
  2642. # end_index = j-1
  2643. # break
  2644. # entity_id = "%s_%d_%d_%d"%(doc_id,sentence_index,begin_index,end_index)
  2645. #
  2646. # #去掉标点符号
  2647. # entity_text = re.sub("[,,。:]","",entity_text)
  2648. # 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))
  2649. #
  2650. #
  2651. # #使用正则识别金额
  2652. # entity_type = "money"
  2653. #
  2654. # #money_patten_str = "(([1-9][\d,,]*(?:\.\d+)?[百千万亿]?[\(\)()元整]+)|([零壹贰叁肆伍陆柒捌玖拾佰仟萬億十百千万亿元角分]{3,})|(?:[¥¥]+,?|报价|标价)[(\(]?([万])?元?[)\)]?[::]?.{,7}?([1-9][\d,,]*(?:\.\d+)?(?:,?)[百千万亿]?)|([1-9][\d,,]*(?:\.\d+)?(?:,?)[百千万亿]?)[\((]?([万元]{1,2}))*"
  2655. #
  2656. # list_money_pattern = {"cn":"(()()([零壹贰叁肆伍陆柒捌玖拾佰仟萬億十百千万亿元角分]{3,})())*",
  2657. # "key_word":"((?:[¥¥]+,?|[报标限]价|金额)(?:[(\(]?\s*([万元]*)\s*[)\)]?)\s*[::]?(\s*[^壹贰叁肆伍陆柒捌玖拾佰仟萬億分]{,7}?)([0-9][\d,,]*(?:\.\d+)?(?:,?)[百千万亿元]*)())*",
  2658. # "front_m":"((?:[(\(]?\s*([万元]+)\s*[)\)])\s*[::]?(\s*[^壹贰叁肆伍陆柒捌玖拾佰仟萬億分]{,7}?)([0-9][\d,,]*(?:\.\d+)?(?:,?)[百千万亿元]*)())*",
  2659. # "behind_m":"(()()([0-9][\d,,]*(?:\.\d+)?(?:,?)[百千万亿]*)[\((]?([万元]+)[\))]?)*"}
  2660. #
  2661. # set_begin = set()
  2662. # for pattern_key in list_money_pattern.keys():
  2663. # pattern = re.compile(list_money_pattern[pattern_key])
  2664. # all_match = re.findall(pattern, sentence_text)
  2665. # index = 0
  2666. # for i in range(len(all_match)):
  2667. # if len(all_match[i][0])>0:
  2668. # # print("===",all_match[i])
  2669. # #print(all_match[i][0])
  2670. # unit = ""
  2671. # entity_text = all_match[i][3]
  2672. # if pattern_key in ["key_word","front_m"]:
  2673. # unit = all_match[i][1]
  2674. # else:
  2675. # unit = all_match[i][4]
  2676. # if entity_text.find("元")>=0:
  2677. # unit = ""
  2678. #
  2679. # index += len(all_match[i][0])-len(entity_text)-len(all_match[i][4])#-len(all_match[i][1])-len(all_match[i][2])#整个提出来的作为实体->数字部分作为整体,否则会丢失特征
  2680. #
  2681. # begin_index_temp = index
  2682. # for j in range(len(list_tokenbegin)):
  2683. # if list_tokenbegin[j]==index:
  2684. # begin_index = j
  2685. # break
  2686. # elif list_tokenbegin[j]>index:
  2687. # begin_index = j-1
  2688. # break
  2689. # index += len(str(entity_text))+len(all_match[i][4])#+len(all_match[i][2])+len(all_match[i][1])#整个提出来的作为实体
  2690. # end_index_temp = index
  2691. # #index += len(str(all_match[i][0]))
  2692. # for j in range(begin_index,len(list_tokenbegin)):
  2693. # if list_tokenbegin[j]>=index:
  2694. # end_index = j-1
  2695. # break
  2696. # entity_id = "%s_%d_%d_%d"%(doc_id,sentence_index,begin_index,end_index)
  2697. #
  2698. #
  2699. # entity_text = re.sub("[^0-9.零壹贰叁肆伍陆柒捌玖拾佰仟萬億十百千万亿元角分]","",entity_text)
  2700. # if len(unit)>0:
  2701. # entity_text = str(getUnifyMoney(entity_text)*getMultipleFactor(unit[0]))
  2702. # else:
  2703. # entity_text = str(getUnifyMoney(entity_text))
  2704. #
  2705. # _exists = False
  2706. # for item in list_sentence_entitys:
  2707. # if item.entity_id==entity_id and item.entity_type==entity_type:
  2708. # _exists = True
  2709. # if not _exists:
  2710. # if float(entity_text)>10:
  2711. # 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))
  2712. #
  2713. # else:
  2714. # index += 1
  2715. #
  2716. # list_sentence_entitys.sort(key=lambda x:x.begin_index)
  2717. # list_entitys_temp = list_entitys_temp+list_sentence_entitys
  2718. # list_sentences.append(list_sentences_temp)
  2719. # list_entitys.append(list_entitys_temp)
  2720. # return list_articles,list_sentences,list_entitys,cost_time
  2721. def get_preprocessed(articles, useselffool=False):
  2722. '''
  2723. @summary:预处理步骤,NLP处理、实体识别
  2724. @param:
  2725. articles:待处理的文章list [[id,source,jointime,doc_id,title]]
  2726. @return:list of articles,list of each article of sentences,list of each article of entitys
  2727. '''
  2728. cost_time = dict()
  2729. list_articles = get_preprocessed_article(articles,cost_time)
  2730. list_sentences,list_outlines = get_preprocessed_sentences(list_articles,True,cost_time)
  2731. list_entitys = get_preprocessed_entitys(list_sentences,True,cost_time)
  2732. calibrateEnterprise(list_articles,list_sentences,list_entitys)
  2733. return list_articles,list_sentences,list_entitys,list_outlines,cost_time
  2734. def special_treatment(sourceContent, web_source_no):
  2735. try:
  2736. if web_source_no == 'DX000202-1':
  2737. ser = re.search('中标供应商及中标金额:【(([\w()]{5,20}-[\d,.]+,)+)】', sourceContent)
  2738. if ser:
  2739. new = ""
  2740. l = ser.group(1).split(',')
  2741. for i in range(len(l)):
  2742. it = l[i]
  2743. if '-' in it:
  2744. role, money = it.split('-')
  2745. new += '标段%d, 中标供应商: ' % (i + 1) + role + ',中标金额:' + money + '。'
  2746. sourceContent = sourceContent.replace(ser.group(0), new, 1)
  2747. elif web_source_no == '00753-14':
  2748. body = sourceContent.find("body")
  2749. body_child = body.find_all(recursive=False)
  2750. pcontent = body
  2751. if 'id' in body_child[0].attrs:
  2752. if len(body_child) <= 2 and body_child[0]['id'] == 'pcontent':
  2753. pcontent = body_child[0]
  2754. # pcontent = sourceContent.find("div", id="pcontent")
  2755. pcontent = pcontent.find_all(recursive=False)[0]
  2756. first_table = None
  2757. for idx in range(len(pcontent.find_all(recursive=False))):
  2758. t_part = pcontent.find_all(recursive=False)[idx]
  2759. if t_part.name != "table":
  2760. break
  2761. if idx == 0:
  2762. first_table = t_part
  2763. else:
  2764. for _tr in t_part.find("tbody").find_all(recursive=False):
  2765. first_table.find("tbody").append(_tr)
  2766. t_part.clear()
  2767. elif web_source_no == 'DX008357-11':
  2768. body = sourceContent.find("body")
  2769. body_child = body.find_all(recursive=False)
  2770. pcontent = body
  2771. if 'id' in body_child[0].attrs:
  2772. if len(body_child) <= 2 and body_child[0]['id'] == 'pcontent':
  2773. pcontent = body_child[0]
  2774. # pcontent = sourceContent.find("div", id="pcontent")
  2775. pcontent = pcontent.find_all(recursive=False)[0]
  2776. error_table = []
  2777. is_error_table = False
  2778. for part in pcontent.find_all(recursive=False):
  2779. if is_error_table:
  2780. if part.name == "table":
  2781. error_table.append(part)
  2782. else:
  2783. break
  2784. if part.name == "div" and part.get_text(strip=True) == "中标候选单位:":
  2785. is_error_table = True
  2786. first_table = None
  2787. for idx in range(len(error_table)):
  2788. t_part = error_table[idx]
  2789. # if t_part.name != "table":
  2790. # break
  2791. if idx == 0:
  2792. for _tr in t_part.find("tbody").find_all(recursive=False):
  2793. if _tr.get_text(strip=True) == "":
  2794. _tr.decompose()
  2795. first_table = t_part
  2796. else:
  2797. for _tr in t_part.find("tbody").find_all(recursive=False):
  2798. if _tr.get_text(strip=True) != "":
  2799. first_table.find("tbody").append(_tr)
  2800. t_part.clear()
  2801. elif web_source_no == '18021-2':
  2802. body = sourceContent.find("body")
  2803. body_child = body.find_all(recursive=False)
  2804. pcontent = body
  2805. if 'id' in body_child[0].attrs:
  2806. if len(body_child) <= 2 and body_child[0]['id'] == 'pcontent':
  2807. pcontent = body_child[0]
  2808. # pcontent = sourceContent.find("div", id="pcontent")
  2809. td = pcontent.find_all("td")
  2810. for _td in td:
  2811. if str(_td.string).strip() == "报价金额":
  2812. _td.string = "单价"
  2813. elif web_source_no == '13740-2':
  2814. # “xxx成为成交供应商”
  2815. re_match = re.search("[^,。]+成为[^,。]*成交供应商", sourceContent)
  2816. if re_match:
  2817. sourceContent = sourceContent.replace(re_match.group(), "成交人:" + re_match.group())
  2818. elif web_source_no == '03786-10':
  2819. ser1 = re.search('中标价:([\d,.]+)', sourceContent)
  2820. ser2 = re.search('合同金额[((]万元[))]:([\d,.]+)', sourceContent)
  2821. if ser1 and ser2:
  2822. m1 = ser1.group(1).replace(',', '')
  2823. m2 = ser2.group(1).replace(',', '')
  2824. if float(m1) < 100000 and (m1.split('.')[0] == m2.split('.')[0] or m2 == '0'):
  2825. new = '中标价(万元):' + m1
  2826. sourceContent = sourceContent.replace(ser1.group(0), new, 1)
  2827. elif web_source_no=='00076-4':
  2828. ser = re.search('主要标的数量:([0-9一]+)\w{,3},主要标的单价:([\d,.]+)元?,合同金额:(.00),', sourceContent)
  2829. if ser:
  2830. num = ser.group(1).replace('一', '1')
  2831. try:
  2832. num = 1 if num == '0' else num
  2833. unit_price = ser.group(2).replace(',', '')
  2834. total_price = str(int(num) * float(unit_price))
  2835. new = '合同金额:' + total_price
  2836. sourceContent = sourceContent.replace('合同金额:.00', new, 1)
  2837. except Exception as e:
  2838. log('preprocessing.py special_treatment exception')
  2839. elif web_source_no=='DX000105-2':
  2840. if re.search("成交公示", sourceContent) and re.search(',投标人:', sourceContent) and re.search(',成交人:', sourceContent)==None:
  2841. sourceContent = sourceContent.replace(',投标人:', ',成交人:')
  2842. elif web_source_no in ['03795-1', '03795-2']:
  2843. if re.search('中标单位如下', sourceContent) and re.search(',投标人:', sourceContent) and re.search(',中标人:', sourceContent)==None:
  2844. sourceContent = sourceContent.replace(',投标人:', ',中标人:')
  2845. elif web_source_no in ['04080-3', '04080-4']:
  2846. ser = re.search('合同金额:([0-9,]+.[0-9]{3,})(.{,4})', sourceContent)
  2847. if ser and '万' not in ser.group(2):
  2848. sourceContent = sourceContent.replace('合同金额:', '合同金额(万元):')
  2849. elif web_source_no=='03761-3':
  2850. ser = re.search('中标价,([0-9]+)[.0-9]*%', sourceContent)
  2851. if ser and int(ser.group(1))>100:
  2852. sourceContent = sourceContent.replace(ser.group(0), ser.group(0)[:-1]+'元')
  2853. elif web_source_no=='00695-7':
  2854. ser = re.search('支付金额:', sourceContent)
  2855. if ser:
  2856. sourceContent = sourceContent.replace('支付金额:', '合同金额:')
  2857. elif web_source_no=='00811-8':
  2858. if re.search('是否中标:是', sourceContent) and re.search('排名:\d,', sourceContent):
  2859. sourceContent = re.sub('排名:\d,', '候选', sourceContent)
  2860. elif web_source_no=='DX000726-6':
  2861. sourceContent = re.sub('卖方[::\s]+宝山钢铁股份有限公司', '招标单位:宝山钢铁股份有限公司', sourceContent)
  2862. elif web_source_no=='DX008791-1':
  2863. sourceContent = re.sub('收货单位:', '最终用户:', sourceContent)
  2864. elif web_source_no=='DX011971':
  2865. sourceContent = re.sub('公司主体:', '业主单位:', sourceContent)
  2866. return sourceContent
  2867. except Exception as e:
  2868. log('特殊数据源: %s 预处理特别修改抛出异常: %s'%(web_source_no, e))
  2869. return sourceContent
  2870. def article_limit(soup,limit_words=30000):
  2871. sub_space = re.compile("\s+")
  2872. def soup_limit(_soup,_count,max_count=30000,max_gap=500):
  2873. """
  2874. :param _soup: soup
  2875. :param _count: 当前字数
  2876. :param max_count: 字数最大限制
  2877. :param max_gap: 超过限制后的最大误差
  2878. :return:
  2879. """
  2880. _gap = _count - max_count
  2881. _is_skip = False
  2882. next_soup = None
  2883. # 跳过层级结构为1的标签,向下取值
  2884. while len(_soup.find_all(recursive=False)) == 1 and \
  2885. _soup.get_text(strip=True) == _soup.find_all(recursive=False)[0].get_text(strip=True):
  2886. _soup = _soup.find_all(recursive=False)[0]
  2887. # 无结构的纯文本直接取值
  2888. if len(_soup.find_all(recursive=False)) == 0:
  2889. _soup.string = str(_soup.get_text())[:max_count-_count]
  2890. _count += len(re.sub(sub_space, "", _soup.string))
  2891. _gap = _count - max_count
  2892. next_soup = None
  2893. else:
  2894. for _soup_part in _soup.find_all(recursive=False):
  2895. if not _is_skip:
  2896. _count += len(re.sub(sub_space, "", _soup_part.get_text()))
  2897. if _count >= max_count:
  2898. _gap = _count - max_count
  2899. if _gap <= max_gap:
  2900. _is_skip = True
  2901. else:
  2902. _is_skip = True
  2903. next_soup = _soup_part
  2904. _count -= len(re.sub(sub_space, "", _soup_part.get_text()))
  2905. continue
  2906. else:
  2907. _soup_part.decompose()
  2908. return _count,_gap,next_soup
  2909. text_count = 0
  2910. have_attachment = False
  2911. attachment_part = None
  2912. for child in soup.find_all(recursive=True):
  2913. if child.name == 'div' and 'class' in child.attrs:
  2914. if "richTextFetch" in child['class']:
  2915. child.insert_before("##attachment##。") # 句号分开,避免项目名称等提取
  2916. attachment_part = child
  2917. have_attachment = True
  2918. break
  2919. if not have_attachment:
  2920. # 无附件,通过get_text()方法与limit_words大小判断是否要限制字数
  2921. if len(re.sub(sub_space, "", soup.get_text())) > limit_words:
  2922. text_count,gap,n_soup = soup_limit(soup,text_count,max_count=limit_words,max_gap=1000)
  2923. while n_soup:
  2924. text_count, gap, n_soup = soup_limit(n_soup, text_count, max_count=limit_words, max_gap=1000)
  2925. else:
  2926. # 有附件
  2927. _text = re.sub(sub_space, "", soup.get_text())
  2928. _text_split = _text.split("##attachment##")
  2929. # 正文部分
  2930. if len(_text_split[0])>limit_words:
  2931. main_soup = attachment_part.parent
  2932. main_text = main_soup.find_all(recursive=False)[0]
  2933. text_count, gap, n_soup = soup_limit(main_text, text_count, max_count=limit_words, max_gap=1000)
  2934. while n_soup:
  2935. text_count, gap, n_soup = soup_limit(n_soup, text_count, max_count=limit_words, max_gap=1000)
  2936. # 附件部分
  2937. if len(_text_split[1])>limit_words:
  2938. # attachment_html纯文本,无子结构
  2939. if len(attachment_part.find_all(recursive=False))==0:
  2940. attachment_part.string = str(attachment_part.get_text())[:limit_words]
  2941. else:
  2942. attachment_text_nums = 0
  2943. attachment_skip = False
  2944. for part in attachment_part.find_all(recursive=False):
  2945. if not attachment_skip:
  2946. if part.name == 'div' and 'filemd5' in part.attrs:
  2947. for p_part in part.find_all(recursive=False):
  2948. last_attachment_text_nums = attachment_text_nums
  2949. attachment_text_nums = attachment_text_nums + len(re.sub(sub_space, "", p_part.get_text()))
  2950. if not attachment_skip:
  2951. if attachment_text_nums >= limit_words:
  2952. p_part.string = str(p_part.get_text())[:limit_words - last_attachment_text_nums]
  2953. attachment_skip = True
  2954. else:
  2955. p_part.decompose()
  2956. # attachment_text_nums, gap, n_part = soup_limit(part, attachment_text_nums,
  2957. # max_count=limit_words,max_gap=1000)
  2958. # while n_part:
  2959. # attachment_text_nums, gap, n_part = soup_limit(n_part, attachment_text_nums,
  2960. # max_count=limit_words,max_gap=1000)
  2961. # print(attachment_text_nums)
  2962. else:
  2963. last_attachment_text_nums = attachment_text_nums
  2964. attachment_text_nums = attachment_text_nums + len(re.sub(sub_space, "", part.get_text()))
  2965. if attachment_text_nums>=limit_words and not attachment_skip:
  2966. part.string = str(part.get_text())[:limit_words-last_attachment_text_nums]
  2967. attachment_skip = True
  2968. else:
  2969. part.decompose()
  2970. return soup
  2971. def attachment_filelink(soup):
  2972. have_attachment = False
  2973. attachment_part = None
  2974. for child in soup.find_all(recursive=True):
  2975. if child.name == 'div' and 'class' in child.attrs:
  2976. if "richTextFetch" in child['class']:
  2977. attachment_part = child
  2978. have_attachment = True
  2979. break
  2980. if not have_attachment:
  2981. return soup
  2982. else:
  2983. # 附件类型:图片、表格
  2984. attachment_type = re.compile("\.(?:png|jpg|jpeg|tif|bmp|xlsx|xls)$")
  2985. attachment_dict = dict()
  2986. for _attachment in attachment_part.find_all(recursive=False):
  2987. if _attachment.name == 'div' and 'filemd5' in _attachment.attrs:
  2988. # print('filemd5',_attachment['filemd5'])
  2989. attachment_dict[_attachment['filemd5']] = _attachment
  2990. # print(attachment_dict)
  2991. for child in soup.find_all(recursive=True):
  2992. if child.name == 'div' and 'class' in child.attrs:
  2993. if "richTextFetch" in child['class']:
  2994. break
  2995. if "filelink" in child.attrs and child['filelink'] in attachment_dict:
  2996. if re.search(attachment_type,str(child.string).strip()) or \
  2997. ('original' in child.attrs and re.search(attachment_type,str(child['original']).strip())) or \
  2998. ('href' in child.attrs and re.search(attachment_type,str(child['href']).strip())):
  2999. # 附件插入正文标识
  3000. child.insert_before("。##attachment_begin##")
  3001. child.insert_after("。##attachment_end##")
  3002. child.replace_with(attachment_dict[child['filelink']])
  3003. # print('格式化输出',soup.prettify())
  3004. return soup
  3005. def del_achievement(text):
  3006. if re.search('中标|成交|入围|结果|评标|开标|候选人', text[:500]) == None or re.search('业绩', text) == None:
  3007. return text
  3008. p0 = '[,。;]((\d{1,2})|\d{1,2}、)[\w、]{,8}:|((\d{1,2})|\d{1,2}、)|。' # 例子 264392818
  3009. p1 = '业绩[:,](\d、[-\w()、]{6,30}(工程|项目|勘察|设计|施工|监理|总承包|采购|更新)[\w()]{,10}[,;])+' # 例子 257717618
  3010. p2 = '(类似业绩情况:|业绩:)(\w{,20}:)?(((\d)|\d、)项目名称:[-\w(),;、\d\s:]{5,100}[;。])+' # 例子 264345826
  3011. p3 = '(投标|类似|(类似)?项目|合格|有效|企业|工程)?业绩(名称|信息|\d)?:(项目名称:)?[-\w()、]{6,50}(项目|工程|勘察|设计|施工|监理|总承包|采购|更新)'
  3012. l = []
  3013. tmp = []
  3014. for it in re.finditer(p0, text):
  3015. if it.group(0)[-3:] in ['业绩:', '荣誉:']:
  3016. if tmp != []:
  3017. del_text = text[tmp[0]:it.start()]
  3018. l.append(del_text)
  3019. tmp = []
  3020. tmp.append(it.start())
  3021. elif tmp != []:
  3022. del_text = text[tmp[0]:it.start()]
  3023. l.append(del_text)
  3024. tmp = []
  3025. if tmp != []:
  3026. del_text = text[tmp[0]:]
  3027. l.append(del_text)
  3028. for del_text in l:
  3029. text = text.replace(del_text, '')
  3030. # print('删除业绩信息:', del_text)
  3031. for rs in re.finditer(p1, text):
  3032. # print('删除业绩信息:', rs.group(0))
  3033. text = text.replace(rs.group(0), '')
  3034. for rs in re.finditer(p2, text):
  3035. # print('删除业绩信息:', rs.group(0))
  3036. text = text.replace(rs.group(0), '')
  3037. for rs in re.finditer(p3, text):
  3038. # print('删除业绩信息:', rs.group(0))
  3039. text = text.replace(rs.group(0), '')
  3040. return text
  3041. def split_header(soup):
  3042. '''
  3043. 处理 空格分割多个表头的情况 : 主要标的名称 规格型号(或服务要求) 主要标的数量 主要标的单价 合同金额(万元)
  3044. :param soup: bs4 soup 对象
  3045. :return:
  3046. '''
  3047. header = []
  3048. attrs = []
  3049. flag = 0
  3050. tag = None
  3051. for p in soup.find_all('p'):
  3052. text = p.get_text()
  3053. if re.search('主要标的数量\s+主要标的单价((万?元))?\s+合同金额', text):
  3054. header = re.split('\s{3,}', text) if re.search('\s{3,}', text) else re.split('\s+', text)
  3055. flag = 1
  3056. tag = p
  3057. tag.string = ''
  3058. continue
  3059. if flag:
  3060. attrs = re.split('\s{3,}', text) if re.search('\s{3,}', text) else re.split('\s+', text)
  3061. if header and len(header) == len(attrs) and tag:
  3062. s = ""
  3063. for head, attr in zip(header, attrs):
  3064. s += head + ':' + attr + ','
  3065. # tag.string = s
  3066. # p.extract()
  3067. p.string = s
  3068. else:
  3069. break
  3070. def get_preprocessed_article(articles,cost_time = dict(),useselffool=True):
  3071. '''
  3072. :param articles: 待处理的article source html
  3073. :param useselffool: 是否使用selffool
  3074. :return: list_articles
  3075. '''
  3076. list_articles = []
  3077. for article in articles:
  3078. doc_id = article[0]
  3079. sourceContent = article[1]
  3080. sourceContent_raw = article[1] # 原始html数据,fingerprint计算MD5用
  3081. sourceContent = re.sub("<html>|</html>|<body>|</body>","",sourceContent)
  3082. sourceContent = re.sub("##attachment##","",sourceContent)
  3083. sourceContent = sourceContent.replace('<br/>', '<br>')
  3084. sourceContent = re.sub("<br>(\s{0,}<br>)+","<br>",sourceContent)
  3085. # for br_match in re.findall("[^>]+?<br>",sourceContent):
  3086. # _new = re.sub("<br>","",br_match)
  3087. # # <br>标签替换为<p>标签
  3088. # if not re.search("^\s+$",_new):
  3089. # _new = '<p>'+_new + '</p>'
  3090. # # print(br_match,_new)
  3091. # sourceContent = sourceContent.replace(br_match,_new,1)
  3092. _send_doc_id = article[3]
  3093. _title = article[4]
  3094. _title_raw = article[4]
  3095. page_time = article[5]
  3096. web_source_no = article[6]
  3097. '''特别数据源对 html 做特别修改'''
  3098. if web_source_no in ['DX000202-1']:
  3099. sourceContent = special_treatment(sourceContent, web_source_no)
  3100. #表格处理
  3101. key_preprocess = "tableToText"
  3102. start_time = time.time()
  3103. # article_processed = tableToText(BeautifulSoup(sourceContent,"lxml"))
  3104. article_processed = BeautifulSoup(sourceContent,"lxml")
  3105. if re.search('主要标的数量(&nbsp;|\s)+主要标的单价((万?元))?(&nbsp;|\s)+合同金额', sourceContent): #处理 空格分割多个表头的情况
  3106. split_header(article_processed)
  3107. '''表格业绩内容删除'''
  3108. del_tabel_achievement(article_processed)
  3109. '''特别数据源对 BeautifulSoup(html) 做特别修改'''
  3110. if web_source_no in ["00753-14","DX008357-11","18021-2"]:
  3111. article_processed = special_treatment(article_processed, web_source_no)
  3112. for _soup in article_processed.descendants:
  3113. # 识别无标签文本,添加<span>标签
  3114. if not _soup.name and not _soup.parent.string and _soup.string.strip()!="":
  3115. # print(_soup.parent.string,_soup.string.strip())
  3116. _soup.wrap(article_processed.new_tag("span"))
  3117. # print(article_processed)
  3118. # 正文和附件内容限制字数30000
  3119. article_processed = article_limit(article_processed, limit_words=30000)
  3120. # 把每个附件识别对应的html放回原来出现的位置
  3121. article_processed = attachment_filelink(article_processed)
  3122. article_processed = get_preprocessed_outline(article_processed)
  3123. # print('article_processed')
  3124. article_processed = tableToText(article_processed)
  3125. # print(article_processed)
  3126. article_processed = segment(article_processed)
  3127. article_processed = article_processed.replace('(', '(').replace(')', ')') #2022/8/10 统一为中文括号
  3128. article_processed = article_processed.replace('侯选人', '候选人') #2024/09/03 修复错别字避免预测错误。
  3129. article_processed = article_processed.replace('人选人', '入选人') #2024/09/03 修复错别字避免预测错误。
  3130. article_processed = article_processed.replace('⺠', '民') # 2025/02/17 修复错别字 例:连云港市第一人⺠医院。
  3131. # article_processed = article_processed.replace(':', ':') #2023/1/5 统一为中文冒号
  3132. article_processed = re.sub("(?<=[\u4e00-\u9fa5]):|:(?=[\u4e00-\u9fa5])", ":", article_processed)
  3133. article_processed = article_processed.replace('.','.').replace('-', '-') # 2021/12/01 修正OCR识别PDF小数点错误问题
  3134. article_processed = article_processed.replace('报价限价', '招标限价') #2021/12/17 由于报价限价预测为中投标金额所以修改
  3135. article_processed = article_processed.replace('成交工程价款', '成交工程价') # 2021/12/21 修正为中标价
  3136. article_processed = re.sub('任务(?=编号[::])', '项目',article_processed) # 2022/08/10 修正为项目编号
  3137. article_processed = article_processed.replace('招标(建设)单位', '招标单位') #2022/8/10 修正预测不到表达
  3138. # article_processed = re.sub("采购商(?=[^\u4e00-\u9fa5]|名称)", "招标人", article_processed) # 20250227注销,避免588296281 03338-7 始兴县人民政府 成交信息:采购商名称: 其实是中标人
  3139. article_processed = re.sub('(招标|采购)人(概况|信息):?[,。]', '采购人信息:', article_processed) # 2022/8/10统一表达
  3140. article_processed = article_processed.replace('\(%)', '') # 中标(成交)金额(元)\(%):498888.00, 处理 江西省政府采购网 金额特殊问题
  3141. article_processed = re.sub('金额:?((可填写下浮率?、折扣率?或费率|拟签含税总单价总计|[^万元()\d]{8,20})))?:?', '金额:', article_processed) # 中标(成交)金额:(可填写下浮率、折扣率或费率):29.3万元 金额特殊问题 例:530377517
  3142. article_processed = re.sub('(不?含(可抵扣增值|\w{,8})税)', '', article_processed) # 120637247 投标报价(元),(含可抵扣增值税):277,560.00。
  3143. article_processed = re.sub('供应商的?(名称[及其、]{1,2}地址|联系方式:名称)', '供应商名称', article_processed) # 18889217, 84422177
  3144. article_processed = re.sub(',最高有效报价者:', ',中标人名称:', article_processed) # 224678159 # 2023/7/4 四川站源特殊中标修改
  3145. article_processed = re.sub(',最高有效报价:', ',投标报价:', article_processed) # 224678159 # 2023/7/4 四川站源特殊中标修改
  3146. article_processed = re.sub('备选中标人', '第二候选人', article_processed) # 341344142 # 2023/7/17 特殊表达修改
  3147. article_processed = re.sub('例:建设银行(甲方全称)', ' ', article_processed) # 2024/06/12 特殊表达修改 修改 481513912 金采网 附件模板导致错误提取招标人
  3148. article_processed = re.sub('^[,,.。;;、]+', '', article_processed)
  3149. article_processed = re.sub('资,金', '资金', article_processed)
  3150. article_processed = re.sub('金,额', '金额', article_processed)
  3151. article_processed = re.sub('存,款', '存款', article_processed)
  3152. article_processed = re.sub('(适用于采用评定分离评标的项目)|(根据需要可以填写总价、单价、下浮率、费率等)|业绩(响应招标文件的业绩,多项应分别列出)', '', article_processed) # 修复关键词过远导致召回失败 例:579672495
  3153. if web_source_no.startswith('DX002756-'):
  3154. article_processed = re.sub('状态:(进行中|已结束)单位', ',项目单位', article_processed) # 376225646
  3155. if web_source_no.startswith('DX006116-') and re.search('结果公告如下:.{5,50},单位名称:', article_processed): # 2023/11/20 特殊处理 381591924 381592533 这种提取不到情况
  3156. article_processed = re.sub(',单位名称:', ',供应商名称:', article_processed)
  3157. ser = re.search('(采购|招标|比选)人(名称)?/(采购|招标|比选)?代理机构(名称)?:(?P<tenderee>[\w()]{4,25}(/[\w()]{4,25})?)/(?P<agency>[\w()]{4,25})[,。]', article_processed)
  3158. if ser:
  3159. article_processed = article_processed.replace(ser.group(0), '采购人名称:%s,采购代理机构名称:%s,' % (ser.group('tenderee'), ser.group('agency')))
  3160. ser2 = re.search('(采购|招标)人(名称)?/(采购|招标)?代理机构(名称)?:(?P<tenderee>[\w()]{4,25})[,。/]', article_processed)
  3161. if ser2:
  3162. article_processed = article_processed.replace(ser2.group(0), '采购人名称:%s,采购代理机构名称:,' % (
  3163. ser2.group('tenderee')))
  3164. if re.search('中标单位名称:[\w()]{5,25},中标候选人名次:\d,', article_processed) and re.search('中标候选人名次:\d,中标单位名称:[\w()]{5,25},', article_processed)==None: # 处理类似 304706608 此篇的数据源正文特殊表达
  3165. for it in re.finditer('(?P<tenderer>(中标单位名称:[\w()]{5,25},))(?P<rank>(中标候选人名次:\d,))', article_processed):
  3166. article_processed = article_processed.replace(it.group(0), it.group('rank')+it.group('tenderer'))
  3167. ser = re.search('竞得人:\d{8,15}-', article_processed)
  3168. if ser:
  3169. article_processed = article_processed.replace(ser.group(0), '竞得人:') # 修复类似 368120777 关键词角色被编号隔开情况
  3170. article_processed = re.sub("流出方信息:。", "流出方信息:", article_processed) # 修复 367520674 产权批量表格问题
  3171. idx = article_processed.find('供应商报名、缴纳保证金、下载采购文件流程.docx。##attachment##。') # 修复404230599 E交易站源批量附件中标人错误
  3172. if idx > 1000:
  3173. article_processed = article_processed[:idx]
  3174. for it in re.finditer('[一二三四五六七八九十\d]、中标候选人名称,', article_processed): # 修复大纲类标点导致提取不到,例:515521734
  3175. article_processed = re.sub(it.group(0), it.group(0)[:-1]+':', article_processed)
  3176. ser = re.search('项目[编代][码号]/项目名称:(?P<code>(\[审批\])?[\d\-]{10,30})/?(?P<name>[\u4e00-\u9fa5()]{4,35}[,。])', article_processed) # 优化项目编号名称一起写的情况 spxm-53340116.html
  3177. if ser:
  3178. article_processed = article_processed.replace(ser.group(0), '项目代码:%s,项目名称:%s' % (
  3179. ser.group('code'), ser.group('name')))
  3180. article_processed = re.sub('四舍五入至', '', article_processed) # 修复 533537050 ,中标价(四舍五入至万元):6468万元
  3181. if re.search('推荐供应商:', article_processed) and re.search('入围供应商:', article_processed): # 修复 中国工商银行 类网站 入围的才算中标
  3182. article_processed = article_processed.replace('推荐供应商:', '公司名称:')
  3183. if web_source_no.startswith('DX016489') and re.search('排名', article_processed) and re.search('成交供应商单位名称', article_processed): # 20250219 处理特殊站源有排名却叫成交供应商
  3184. article_processed = article_processed.replace('成交供应商单位名称', '成交候选人单位名称')
  3185. if web_source_no.startswith('DX003027') and re.search('招标单位:中招联合信息股份有限公司', article_processed): # 20250402 处理站源招标人错误 明信阳光采购网
  3186. article_processed = article_processed.replace('招标单位:中招联合信息股份有限公司', '')
  3187. '''去除业绩内容'''
  3188. article_processed = del_achievement(article_processed)
  3189. # 修复OCR金额中“,”、“。”识别错误
  3190. article_processed_list = article_processed.split("##attachment##")
  3191. if len(article_processed_list)>1:
  3192. attachment_text = article_processed_list[1]
  3193. for _match in re.finditer("\d。\d{2}",attachment_text):
  3194. _match_text = _match.group()
  3195. attachment_text = attachment_text.replace(_match_text,_match_text.replace("。","."),1)
  3196. # for _match in re.finditer("(\d,\d{3})[,,.]",attachment_text):
  3197. for _match in re.finditer("\d,(?=\d{3}[^\d])",attachment_text):
  3198. _match_text = _match.group()
  3199. attachment_text = attachment_text.replace(_match_text,_match_text.replace(",",","),1)
  3200. article_processed_list[1] = attachment_text
  3201. article_processed = "##attachment##".join(article_processed_list)
  3202. '''特别数据源对 预处理后文本 做特别修改'''
  3203. 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', 'DX000726-6','DX008791-1','DX011971']:
  3204. article_processed = special_treatment(article_processed, web_source_no)
  3205. # 提取bidway
  3206. list_bidway = extract_bidway(article_processed, _title)
  3207. if list_bidway:
  3208. bidway = list_bidway[0].get("body")
  3209. # bidway名称统一规范
  3210. bidway = bidway_integrate(bidway)
  3211. else:
  3212. bidway = ""
  3213. # 修正被","逗号分隔的时间
  3214. repair_time = re.compile("[12]\d,?\d,?\d,?[-—-―/年],?[0-1]?\d,?[-—-―/月],?[0-3]?\d,?[日号]?,?(?:上午|下午)?,?[0-2]?\d,?:,?[0-6]\d,?:,?[0-6]\d|"
  3215. "[12]\d,?\d,?\d,?[-—-―/年],?[0-1]?\d,?[-—-―/月],?[0-3]?\d,?[日号]?,?(?:上午|下午)?,?[0-2]?\d,?[:时点],?[0-6]\d分?|"
  3216. "[12]\d,?\d,?\d,?[-—-―/年],?[0-1]?\d,?[-—-―/月],?[0-3]?\d,?[日号]?,?(?:上午|下午)?,?[0-2]?\d,?[时点]|"
  3217. "[12]\d,?\d,?\d,?[-—-―/年],?[0-1]?\d,?[-—-―/月],?[0-3]?\d,?[日号]|"
  3218. "[0-2]?\d,?:,?[0-6]\d,?:,?[0-6]\d"
  3219. )
  3220. for _time in set(re.findall(repair_time,article_processed)):
  3221. if re.search(",",_time):
  3222. _time2 = re.sub(",", "", _time)
  3223. item = re.search("[12]\d{3}[-—-―/][0-1]?\d[-—-―/][0-3]\d(?=\d)", _time2)
  3224. if item:
  3225. _time2 = _time2.replace(item.group(),item.group() + " ")
  3226. article_processed = article_processed.replace(_time, _time2)
  3227. else:
  3228. item = re.search("[12]\d{3}[-—-―/][0-1]?\d[-—-―/][0-3]\d(?=\d)", _time)
  3229. if item:
  3230. _time2 = _time.replace(item.group(),item.group() + " ")
  3231. article_processed = article_processed.replace(_time, _time2)
  3232. # print('re_rtime',re.findall(repair_time,article_processed))
  3233. # log(article_processed)
  3234. if key_preprocess not in cost_time:
  3235. cost_time[key_preprocess] = 0
  3236. cost_time[key_preprocess] += round(time.time()-start_time,2)
  3237. #article_processed = article[1]
  3238. _article = Article(doc_id,article_processed,sourceContent,_send_doc_id,_title,
  3239. bidway=bidway)
  3240. _article.fingerprint = getFingerprint(_title_raw+sourceContent_raw)
  3241. _article.page_time = page_time
  3242. list_articles.append(_article)
  3243. return list_articles
  3244. def get_preprocessed_sentences(list_articles,useselffool=True,cost_time=dict()):
  3245. '''
  3246. :param list_articles: 经过预处理的article text
  3247. :return: list_sentences
  3248. '''
  3249. list_sentences = []
  3250. list_outlines = []
  3251. for article in list_articles:
  3252. list_sentences_temp = []
  3253. list_entitys_temp = []
  3254. doc_id = article.id
  3255. _send_doc_id = article.doc_id
  3256. _title = article.title
  3257. #表格处理
  3258. key_preprocess = "tableToText"
  3259. start_time = time.time()
  3260. article_processed = article.content
  3261. if len(_title)<100 and _title not in article_processed: # 把标题放到正文
  3262. article_processed = _title + ',' + article_processed # 2023/01/06 标题正文加逗号分割,预防标题后面是产品,正文开头是公司实体,实体识别把产品和公司作为整个角色实体
  3263. attachment_begin_index = -1
  3264. if key_preprocess not in cost_time:
  3265. cost_time[key_preprocess] = 0
  3266. cost_time[key_preprocess] += time.time()-start_time
  3267. #nlp处理
  3268. outline_list = [] # 20240906 修复下面条件不成立时,后面 list_outlines.append(outline_list) 名称未定义报错
  3269. if article_processed is not None and len(article_processed)!=0:
  3270. split_patten = "。"
  3271. sentences = []
  3272. _begin = 0
  3273. sentences_set = set()
  3274. for _iter in re.finditer(split_patten,article_processed):
  3275. _sen = article_processed[_begin:_iter.span()[1]]
  3276. # if len(_sen)>0 and _sen not in sentences_set: # 去重导致内容丢失
  3277. if len(_sen)>0 and (len(sentences)>0 and _sen != sentences[-1] or len(sentences)==0): # 2024/07/25 改为顺序去重
  3278. # 标识在附件里的句子
  3279. if re.search("##attachment##",_sen):
  3280. attachment_begin_index = len(sentences)
  3281. # _sen = re.sub("##attachment##","",_sen)
  3282. sentences.append(_sen)
  3283. sentences_set.add(_sen)
  3284. _begin = _iter.span()[1]
  3285. _sen = article_processed[_begin:]
  3286. if re.search("##attachment##", _sen):
  3287. # _sen = re.sub("##attachment##", "", _sen)
  3288. attachment_begin_index = len(sentences)
  3289. # if len(_sen)>0 and _sen not in sentences_set:
  3290. if len(_sen)>0 and (len(sentences)>0 and _sen != sentences[-1] or len(sentences)==0): # 2024/07/25 改为顺序去重
  3291. sentences.append(_sen)
  3292. sentences_set.add(_sen)
  3293. # 解析outline大纲分段
  3294. outline_list = []
  3295. if re.search("##split##",article.content):
  3296. temp_sentences = []
  3297. last_sentence_index = (-1,-1)
  3298. outline_index = 0
  3299. for sentence_index in range(len(sentences)):
  3300. sentence_text = sentences[sentence_index]
  3301. for _ in re.findall("##split##", sentence_text):
  3302. _match = re.search("##split##", sentence_text)
  3303. if last_sentence_index[0] > -1:
  3304. sentence_begin_index,wordOffset_begin = last_sentence_index
  3305. sentence_end_index = sentence_index
  3306. wordOffset_end = _match.start()
  3307. if sentence_begin_index<attachment_begin_index and sentence_end_index>=attachment_begin_index:
  3308. outline_list.append(Outline(doc_id,outline_index,'',sentence_begin_index,attachment_begin_index-1,wordOffset_begin,len(sentences[attachment_begin_index-1])))
  3309. else:
  3310. outline_list.append(Outline(doc_id,outline_index,'',sentence_begin_index,sentence_end_index,wordOffset_begin,wordOffset_end))
  3311. outline_index += 1
  3312. sentence_text = re.sub("##split##,?", "", sentence_text,count=1)
  3313. last_sentence_index = (sentence_index,_match.start())
  3314. temp_sentences.append(sentence_text)
  3315. if attachment_begin_index>-1 and last_sentence_index[0]<attachment_begin_index:
  3316. 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])))
  3317. else:
  3318. outline_list.append(Outline(doc_id,outline_index,'',last_sentence_index[0],len(sentences)-1,last_sentence_index[1],len(temp_sentences[-1])))
  3319. sentences = temp_sentences
  3320. #解析outline的outline_text内容
  3321. for _outline in outline_list:
  3322. if _outline.sentence_begin_index==_outline.sentence_end_index:
  3323. _text = sentences[_outline.sentence_begin_index][_outline.wordOffset_begin:_outline.wordOffset_end]
  3324. else:
  3325. _text = ""
  3326. for idx in range(_outline.sentence_begin_index,_outline.sentence_end_index+1):
  3327. if idx==_outline.sentence_begin_index:
  3328. _text += sentences[idx][_outline.wordOffset_begin:]
  3329. elif idx==_outline.sentence_end_index:
  3330. _text += sentences[idx][:_outline.wordOffset_end]
  3331. else:
  3332. _text += sentences[idx]
  3333. _outline.outline_text = _text
  3334. _outline_summary = re.split("[::,]",_text,1)[0]
  3335. if len(_outline_summary)<30:
  3336. _outline.outline_summary = _outline_summary
  3337. # print(_outline.outline_index,_outline.outline_text)
  3338. article.content = "".join(sentences)
  3339. # sentences.append(article_processed[_begin:])
  3340. article.content = re.sub('[,。\s]+。', '。', article.content) # 处理连续标点
  3341. lemmas = []
  3342. doc_offsets = []
  3343. dep_types = []
  3344. dep_tokens = []
  3345. time1 = time.time()
  3346. '''
  3347. tokens_all = fool.cut(sentences)
  3348. #pos_all = fool.LEXICAL_ANALYSER.pos(tokens_all)
  3349. #ner_tag_all = fool.LEXICAL_ANALYSER.ner_labels(sentences,tokens_all)
  3350. ner_entitys_all = fool.ner(sentences)
  3351. '''
  3352. #限流执行
  3353. key_nerToken = "nerToken"
  3354. start_time = time.time()
  3355. # tokens_all = getTokens(sentences,useselffool=useselffool)
  3356. tokens_all = getTokens([re.sub("##attachment_begin##|##attachment_end##","",_sen) for _sen in sentences],useselffool=useselffool)
  3357. if key_nerToken not in cost_time:
  3358. cost_time[key_nerToken] = 0
  3359. cost_time[key_nerToken] += round(time.time()-start_time,2)
  3360. in_attachment = False
  3361. for sentence_index in range(len(sentences)):
  3362. sentence_text = sentences[sentence_index]
  3363. if re.search("##attachment_begin##",sentence_text):
  3364. in_attachment = True
  3365. sentence_text = re.sub("##attachment_begin##","",sentence_text)
  3366. if re.search("##attachment_end##",sentence_text):
  3367. in_attachment = False
  3368. sentence_text = re.sub("##attachment_end##", "", sentence_text)
  3369. if sentence_index >= attachment_begin_index and attachment_begin_index!=-1:
  3370. in_attachment = True
  3371. tokens = tokens_all[sentence_index]
  3372. #pos_tag = pos_all[sentence_index]
  3373. pos_tag = ""
  3374. ner_entitys = ""
  3375. 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))
  3376. if len(list_sentences_temp)==0:
  3377. list_sentences_temp.append(Sentences(doc_id=doc_id,sentence_index=0,sentence_text="sentence_text",tokens=[],pos_tags=[],ner_tags=""))
  3378. list_sentences.append(list_sentences_temp)
  3379. list_outlines.append(outline_list)
  3380. article.content = re.sub("##attachment_begin##|##attachment_end##", "", article.content)
  3381. return list_sentences,list_outlines
  3382. def cut_repeat_name(s):
  3383. '''
  3384. 公司连续重复名称去重
  3385. :param s:
  3386. :return:
  3387. '''
  3388. if len(s) >= 8:
  3389. n = s.count(s[-4:])
  3390. id = s.find(s[-4:]) + 4
  3391. sub_s = s[:id]
  3392. if n>=2 and s == sub_s * n:
  3393. s = sub_s
  3394. return s
  3395. def get_preprocessed_entitys(list_sentences,useselffool=True,cost_time=dict()):
  3396. '''
  3397. :param list_sentences:分局情况
  3398. :param cost_time:
  3399. :return: list_entitys
  3400. '''
  3401. list_entitys = []
  3402. not_extract_roles = ['黄埔军校', '国有资产管理处', '五金建材', '铝合金门窗', '华电XX发电有限公司', '华电XXX发电有限公司', '中标(成交)公司', '贵州茅台', '贵州茅台酒', '陕西省省级国'] # 需要过滤掉的企业单位
  3403. for list_sentence in list_sentences:
  3404. sentences = []
  3405. list_entitys_temp = []
  3406. for _sentence in list_sentence:
  3407. sentences.append(_sentence.sentence_text)
  3408. time1 = time.time()
  3409. '''
  3410. tokens_all = fool.cut(sentences)
  3411. #pos_all = fool.LEXICAL_ANALYSER.pos(tokens_all)
  3412. #ner_tag_all = fool.LEXICAL_ANALYSER.ner_labels(sentences,tokens_all)
  3413. ner_entitys_all = fool.ner(sentences)
  3414. '''
  3415. #限流执行
  3416. key_nerToken = "nerToken"
  3417. start_time = time.time()
  3418. found_yeji = 0 # 2021/8/6 增加判断是否正文包含评标结果 及类似业绩判断用于过滤后面的金额
  3419. # found_pingbiao = False
  3420. ner_entitys_all = getNers(sentences,useselffool=useselffool)
  3421. if key_nerToken not in cost_time:
  3422. cost_time[key_nerToken] = 0
  3423. cost_time[key_nerToken] += round(time.time()-start_time,2)
  3424. doctextcon_sentence_len = sum([1 for sentence in list_sentence if not sentence.in_attachment])
  3425. company_dict = set()
  3426. company_index = dict((i,set()) for i in range(len(list_sentence)))
  3427. for sentence_index in range(len(list_sentence)):
  3428. list_sentence_entitys = []
  3429. sentence_text = list_sentence[sentence_index].sentence_text
  3430. tokens = list_sentence[sentence_index].tokens
  3431. doc_id = list_sentence[sentence_index].doc_id
  3432. in_attachment = list_sentence[sentence_index].in_attachment
  3433. list_tokenbegin = []
  3434. begin = 0
  3435. for i in range(0,len(tokens)):
  3436. list_tokenbegin.append(begin)
  3437. begin += len(str(tokens[i]))
  3438. list_tokenbegin.append(begin+1)
  3439. #pos_tag = pos_all[sentence_index]
  3440. pos_tag = ""
  3441. ner_entitys = ner_entitys_all[sentence_index]
  3442. # 20250320 注释掉下面代码 避免带来异常实体
  3443. # '''正则识别角色实体 经营部|经销部|电脑部|服务部|复印部|印刷部|彩印部|装饰部|修理部|汽修部|修理店|零售店|设计店|服务店|家具店|专卖店|分店|文具行|商行|印刷厂|修理厂|维修中心|修配中心|养护中心|服务中心|会馆|文化馆|超市|门市|商场|家具城|印刷社|经销处'''
  3444. # for it in re.finditer(
  3445. # '(?P<text_key_word>(((单一来源|中标|中选|中价|成交)(供应商|供货商|服务商|候选人|单位|人))|(供应商|供货商|服务商|候选人))(名称)?[为::]+)(?P<text>([()\u4e00-\u9fa5]{5,20})(厂|中心|超市|门市|商场|工作室|文印室|城|部|店|站|馆|行|社|处))[,。]',
  3446. # sentence_text):
  3447. # for k, v in it.groupdict().items():
  3448. # if k == 'text_key_word':
  3449. # keyword = v
  3450. # if k == 'text':
  3451. # entity = v
  3452. # b = it.start() + len(keyword)
  3453. # e = it.end() - 1
  3454. # if (b, e, 'location', entity) in ner_entitys:
  3455. # ner_entitys.remove((b, e, 'location', entity))
  3456. # ner_entitys.append((b, e, 'company', entity))
  3457. # elif (b, e, 'org', entity) not in ner_entitys and (b, e, 'company', entity) not in ner_entitys:
  3458. # ner_entitys.append((b, e, 'company', entity))
  3459. #
  3460. # for it in re.finditer(
  3461. # '(?P<text_key_word>((建设|招租|招标|采购)(单位|人)|业主)(名称)?[为::]+)(?P<text>[\u4e00-\u9fa5]{2,4}[省市县区镇]([()\u4e00-\u9fa5]{2,20})(管理处|办公室|委员会|村委会|纪念馆|监狱|管教所|修养所|社区|农场|林场|羊场|猪场|石场|村|幼儿园|海关|殡仪馆)|海门\w{2,15}村)[,。]',
  3462. # sentence_text):
  3463. # for k, v in it.groupdict().items():
  3464. # if k == 'text_key_word':
  3465. # keyword = v
  3466. # if k == 'text':
  3467. # entity = v
  3468. # b = it.start() + len(keyword)
  3469. # e = it.end() - 1
  3470. # if (b, e, 'location', entity) in ner_entitys:
  3471. # ner_entitys.remove((b, e, 'location', entity))
  3472. # ner_entitys.append((b, e, 'org', entity))
  3473. # if (b, e, 'org', entity) not in ner_entitys and (b, e, 'company', entity) not in ner_entitys:
  3474. # ner_entitys.append((b, e, 'org', entity))
  3475. for ner_entity in ner_entitys:
  3476. if ner_entity[2] in ['company','org']:
  3477. company_dict.add((ner_entity[2],ner_entity[3]))
  3478. company_index[sentence_index].add((ner_entity[0],ner_entity[1]))
  3479. #识别package
  3480. ner_time_list = []
  3481. #识别实体
  3482. for ner_entity in ner_entitys:
  3483. begin_index_temp = ner_entity[0]
  3484. end_index_temp = ner_entity[1]
  3485. entity_type = ner_entity[2]
  3486. entity_text = ner_entity[3]
  3487. if entity_type in ["org", "company"] and re.search('^((特殊)?普通合伙)|^(有限合伙)', sentence_text[end_index_temp:]): # 规则补充合伙关键词
  3488. partnership = re.search('^((特殊)?普通合伙)|^(有限合伙)', sentence_text[end_index_temp:]).group(0)
  3489. end_index_temp += len(partnership)
  3490. entity_text += partnership
  3491. if entity_type == 'location' and re.search('^\w{2,4}[市县]\w{2,15}(中心|监狱|殡仪馆|水利站)$', entity_text) and \
  3492. re.search('\d[楼层号]', entity_text)==None: # 2024/06/07 修改错误地址实体为角色
  3493. entity_type = 'org'
  3494. if begin_index_temp>0 and '县' in entity_text and re.match('前郭尔罗斯蒙古族自治县|积石山县', sentence_text[begin_index_temp-1:end_index_temp]): #20240905 修复实体识别少字问题
  3495. entity_text = sentence_text[begin_index_temp-1] + entity_text
  3496. begin_index_temp -= 1
  3497. ner_entity = (begin_index_temp, end_index_temp, entity_type, entity_text)
  3498. elif entity_text == '中华人民共和国' and re.search('^\w{2,4}海关', sentence_text[end_index_temp: end_index_temp+6]): # 2024/04/24 修复 采购单位:中华人民共和国汕尾海关, 识别不到海关
  3499. ser = re.search('^\w{2,4}海关', sentence_text[end_index_temp: end_index_temp+6])
  3500. entity_text += ser.group(0)
  3501. end_index_temp += ser.end()
  3502. ner_entity = (begin_index_temp, end_index_temp, entity_type, entity_text)
  3503. if entity_type=='time':
  3504. ner_time_list.append((begin_index_temp,end_index_temp))
  3505. if entity_type in ["org","company"] and not isLegalEnterprise(entity_text):
  3506. continue
  3507. # 实体长度限制
  3508. if entity_type in ["org","company"] and len(entity_text)>30:
  3509. continue
  3510. if entity_type == "person" and len(entity_text) > 20:
  3511. continue
  3512. elif entity_type=="person" and len(entity_text)>10 and len(re.findall("[\u4e00-\u9fa5]",entity_text))<len(entity_text)/2:
  3513. continue
  3514. # 识别不完整的组织机构补充
  3515. # if entity_type in ["org"]:
  3516. # end_words = re.search("^[\u4e00-\u9fa5]{,5}(?:办公室|部|中心|处|会)",sentence_text[end_index_temp:end_index_temp+10]) # 2024/4/7 注释掉 273356356 江门市新会区大鳌镇农村集体资产资源交易中心受新会
  3517. # if end_words:
  3518. # entity_text = entity_text + end_words.group()
  3519. for j in range(len(list_tokenbegin)):
  3520. if list_tokenbegin[j]==begin_index_temp:
  3521. begin_index = j
  3522. break
  3523. elif list_tokenbegin[j]>begin_index_temp:
  3524. begin_index = j-1
  3525. break
  3526. begin_index_temp += len(str(entity_text))
  3527. for j in range(begin_index,len(list_tokenbegin)):
  3528. if list_tokenbegin[j]>=begin_index_temp:
  3529. end_index = j-1
  3530. break
  3531. entity_id = "%s_%d_%d_%d"%(doc_id,sentence_index,begin_index,end_index)
  3532. #去掉标点符号
  3533. if entity_type!='time':
  3534. entity_text = re.sub("[,,。:!&@$\*\s;;]","",entity_text) # 215553737
  3535. entity_text = entity_text.replace("(","(").replace(")",")") if isinstance(entity_text,str) else entity_text
  3536. # 组织机构实体名称补充
  3537. if entity_type in ["org", "company"]:
  3538. if entity_text in not_extract_roles: # 过滤掉名称在 需要过滤企业单位列表里的
  3539. continue
  3540. if not re.search("有限责任公司|有限公司",entity_text):
  3541. fix_name = re.search("(有限)([责贵]?任?)(公?司?)",entity_text)
  3542. if fix_name:
  3543. if len(fix_name.group(2))>0:
  3544. _text = fix_name.group()
  3545. if '司' in _text:
  3546. entity_text = entity_text.replace(_text, "有限责任公司")
  3547. else:
  3548. _text = re.search(_text + "[^司]{0,5}司", entity_text)
  3549. if _text:
  3550. _text = _text.group()
  3551. entity_text = entity_text.replace(_text, "有限责任公司")
  3552. else:
  3553. entity_text = entity_text.replace(entity_text[fix_name.start():], "有限责任公司")
  3554. elif len(fix_name.group(3))>0:
  3555. _text = fix_name.group()
  3556. if '司' in _text:
  3557. entity_text = entity_text.replace(_text, "有限公司")
  3558. else:
  3559. _text = re.search(_text + "[^司]{0,3}司", entity_text)
  3560. if _text:
  3561. _text = _text.group()
  3562. entity_text = entity_text.replace(_text, "有限公司")
  3563. else:
  3564. entity_text = entity_text.replace(entity_text[fix_name.start():], "有限公司")
  3565. elif re.search("有限$", entity_text):
  3566. entity_text = re.sub("有限$","有限公司",entity_text)
  3567. entity_text = entity_text.replace("有公司","有限公司")
  3568. '''下面对公司实体进行清洗'''
  3569. entity_text = clean_company(entity_text)
  3570. if entity_text == '':
  3571. continue
  3572. entity_text = cut_repeat_name(entity_text) # 20231201 重复名称去重 如:中山大学附属第一医院中山大学附属第一医院中山大学附属第一医院
  3573. 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))
  3574. # 标记文章末尾的"发布人”、“发布时间”实体
  3575. if sentence_index==len(list_sentence)-1 or sentence_index==doctextcon_sentence_len-1:
  3576. if len(list_sentence_entitys[-2:])==2:
  3577. second2last = list_sentence_entitys[-2]
  3578. last = list_sentence_entitys[-1]
  3579. if (second2last.entity_type in ["company",'org'] and last.entity_type=="time") or (
  3580. second2last.entity_type=="time" and last.entity_type in ["company",'org']):
  3581. if last.wordOffset_begin - second2last.wordOffset_end < 6 and len(sentence_text) - last.wordOffset_end<6:
  3582. last.is_tail = True
  3583. second2last.is_tail = True
  3584. #使用正则识别金额
  3585. money_list, found_yeji = get_money_entity(sentence_text, found_yeji, in_attachment)
  3586. entity_type = "money"
  3587. for money in money_list:
  3588. # print('money: ', money)
  3589. entity_text, begin_index, end_index, unit, notes = money
  3590. end_index = end_index - 1 if entity_text.endswith(',') else end_index
  3591. entity_id = "%s_%d_%d_%d" % (doc_id, sentence_index, begin_index, end_index)
  3592. _exists = False
  3593. for item in list_sentence_entitys:
  3594. if item.entity_id==entity_id and item.entity_type==entity_type:
  3595. _exists = True
  3596. if (begin_index >=item.wordOffset_begin and begin_index<item.wordOffset_end) or (end_index>item.wordOffset_begin and end_index<=item.wordOffset_end):
  3597. _exists = True
  3598. # print('_exists: ',begin_index, end_index, item.wordOffset_begin, item.wordOffset_end, item.entity_text, item.entity_type)
  3599. if not _exists:
  3600. if float(entity_text)>1:
  3601. # if symbol == '-': # 负值金额保留负号
  3602. # entity_text = '-'+entity_text # 20230414 取消符号
  3603. begin_words = changeIndexFromWordToWords(tokens, begin_index)
  3604. end_words = changeIndexFromWordToWords(tokens, end_index)
  3605. # print('金额位置: ', begin_index, begin_words,end_index, end_words)
  3606. # print('金额召回: ', entity_text, sentence_text[begin_index:end_index], tokens[begin_words:end_words])
  3607. list_sentence_entitys.append(Entity(doc_id,entity_id,entity_text,entity_type,sentence_index,begin_words,end_words,begin_index,end_index,in_attachment=in_attachment))
  3608. list_sentence_entitys[-1].notes = notes # 2021/7/20 新增金额备注
  3609. list_sentence_entitys[-1].money_unit = unit # 2021/7/20 新增金额备注
  3610. # print('预处理中的 金额:%s, 单位:%s'%(entity_text,unit))
  3611. # print(entity_text,unit,notes)
  3612. # "联系人"正则补充提取 2021/11/15 新增
  3613. list_person_text = [entity.entity_text for entity in list_sentence_entitys if entity.entity_type=='person']
  3614. error_text = ['交易','机构','教育','项目','公司','中标','开标','截标','监督','政府','国家','中国','技术','投标','传真','网址','电子邮',
  3615. '联系','联系电','联系地','采购代','邮政编','邮政','电话','手机','手机号','联系人','地址','地点','邮箱','邮编','联系方','招标','招标人','代理',
  3616. '代理人','采购','附件','注意','登录','报名','踏勘',"测试",'交货']
  3617. list_person_text = set(list_person_text + error_text)
  3618. re_person = re.compile("联系人[::]([\u4e00-\u9fa5]工)|"
  3619. "联系人[::]([\u4e00-\u9fa5]{2,3})(?=,?联系)|"
  3620. "联系人[::]([\u4e00-\u9fa5]{2,3})(?=[,。;、])"
  3621. )
  3622. list_person = []
  3623. if not in_attachment:
  3624. for match_result in re_person.finditer(sentence_text):
  3625. match_text = match_result.group()
  3626. entity_text = match_text[4:]
  3627. wordOffset_begin = match_result.start() + 4
  3628. wordOffset_end = match_result.end()
  3629. # print(text[wordOffset_begin:wordOffset_end])
  3630. # 排除一些不为人名的实体
  3631. if re.search("^[\u4e00-\u9fa5]{7,}([,。]|$)",sentence_text[wordOffset_begin:wordOffset_begin+20]):
  3632. continue
  3633. if entity_text not in list_person_text and entity_text[:2] not in list_person_text:
  3634. _person = dict()
  3635. _person['body'] = entity_text
  3636. _person['begin_index'] = wordOffset_begin
  3637. _person['end_index'] = wordOffset_end
  3638. list_person.append(_person)
  3639. entity_type = "person"
  3640. for person in list_person:
  3641. begin_index_temp = person['begin_index']
  3642. for j in range(len(list_tokenbegin)):
  3643. if list_tokenbegin[j] == begin_index_temp:
  3644. begin_index = j
  3645. break
  3646. elif list_tokenbegin[j] > begin_index_temp:
  3647. begin_index = j - 1
  3648. break
  3649. index = person['end_index']
  3650. end_index_temp = index
  3651. for j in range(begin_index, len(list_tokenbegin)):
  3652. if list_tokenbegin[j] >= index:
  3653. end_index = j - 1
  3654. break
  3655. entity_id = "%s_%d_%d_%d" % (doc_id, sentence_index, begin_index, end_index)
  3656. entity_text = person['body']
  3657. list_sentence_entitys.append(
  3658. Entity(doc_id, entity_id, entity_text, entity_type, sentence_index, begin_index, end_index,
  3659. begin_index_temp, end_index_temp,in_attachment=in_attachment))
  3660. # 时间实体格式补充
  3661. re_time_new = re.compile("20\d{2}-\d{1,2}-\d{1,2}|20\d{2}/\d{1,2}/\d{1,2}|20\d{2}\.\d{1,2}\.\d{1,2}|20\d{2}(?:0[1-9]|1[0-2])(?:0[1-9]|[1-2][0-9]|3[0-1])")
  3662. entity_type = "time"
  3663. for _time in re.finditer(re_time_new,sentence_text):
  3664. entity_text = _time.group()
  3665. begin_index_temp = _time.start()
  3666. end_index_temp = _time.end()
  3667. is_same = False
  3668. for t_index in ner_time_list:
  3669. if begin_index_temp>=t_index[0] and end_index_temp<=t_index[1]:
  3670. is_same = True
  3671. break
  3672. if is_same:
  3673. continue
  3674. if _time.start()!=0 and re.search("\d",sentence_text[_time.start()-1:_time.start()]):
  3675. continue
  3676. # 纯数字格式,例:20190509
  3677. if re.search("^\d{8}$",entity_text):
  3678. if _time.end()!=len(sentence_text) and re.search("[\da-zA-z]",sentence_text[_time.end():_time.end()+1]):
  3679. continue
  3680. entity_text = entity_text[:4] + "-" + entity_text[4:6] + "-" + entity_text[6:8]
  3681. if not timeFormat(entity_text):
  3682. continue
  3683. for j in range(len(list_tokenbegin)):
  3684. if list_tokenbegin[j] == begin_index_temp:
  3685. begin_index = j
  3686. break
  3687. elif list_tokenbegin[j] > begin_index_temp:
  3688. begin_index = j - 1
  3689. break
  3690. for j in range(begin_index, len(list_tokenbegin)):
  3691. if list_tokenbegin[j] >= end_index_temp:
  3692. end_index = j - 1
  3693. break
  3694. entity_id = "%s_%d_%d_%d" % (doc_id, sentence_index, begin_index, end_index)
  3695. list_sentence_entitys.append(
  3696. Entity(doc_id, entity_id, entity_text, entity_type, sentence_index, begin_index, end_index,
  3697. begin_index_temp, end_index_temp, in_attachment=in_attachment))
  3698. # 资金来源提取 2020/12/30 新增
  3699. list_moneySource = extract_moneySource(sentence_text)
  3700. entity_type = "moneysource"
  3701. for moneySource in list_moneySource:
  3702. entity_text = moneySource['body']
  3703. if len(entity_text)>50:
  3704. continue
  3705. begin_index_temp = moneySource['begin_index']
  3706. for j in range(len(list_tokenbegin)):
  3707. if list_tokenbegin[j] == begin_index_temp:
  3708. begin_index = j
  3709. break
  3710. elif list_tokenbegin[j] > begin_index_temp:
  3711. begin_index = j - 1
  3712. break
  3713. index = moneySource['end_index']
  3714. end_index_temp = index
  3715. for j in range(begin_index, len(list_tokenbegin)):
  3716. if list_tokenbegin[j] >= index:
  3717. end_index = j - 1
  3718. break
  3719. entity_id = "%s_%d_%d_%d" % (doc_id, sentence_index, begin_index, end_index)
  3720. list_sentence_entitys.append(
  3721. Entity(doc_id, entity_id, entity_text, entity_type, sentence_index, begin_index, end_index,
  3722. begin_index_temp, end_index_temp,in_attachment=in_attachment,prob=moneySource['prob']))
  3723. # 电子邮箱提取 2021/11/04 新增
  3724. list_email = extract_email(sentence_text)
  3725. entity_type = "email" # 电子邮箱
  3726. for email in list_email:
  3727. begin_index_temp = email['begin_index']
  3728. for j in range(len(list_tokenbegin)):
  3729. if list_tokenbegin[j] == begin_index_temp:
  3730. begin_index = j
  3731. break
  3732. elif list_tokenbegin[j] > begin_index_temp:
  3733. begin_index = j - 1
  3734. break
  3735. index = email['end_index']
  3736. end_index_temp = index
  3737. for j in range(begin_index, len(list_tokenbegin)):
  3738. if list_tokenbegin[j] >= index:
  3739. end_index = j - 1
  3740. break
  3741. entity_id = "%s_%d_%d_%d" % (doc_id, sentence_index, begin_index, end_index)
  3742. entity_text = email['body']
  3743. list_sentence_entitys.append(
  3744. Entity(doc_id, entity_id, entity_text, entity_type, sentence_index, begin_index, end_index,
  3745. begin_index_temp, end_index_temp,in_attachment=in_attachment))
  3746. # 服务期限提取 2020/12/30 新增
  3747. list_servicetime = extract_servicetime(sentence_text)
  3748. entity_type = "serviceTime"
  3749. for servicetime in list_servicetime:
  3750. entity_text = servicetime['body']
  3751. begin_index_temp = servicetime['begin_index']
  3752. for j in range(len(list_tokenbegin)):
  3753. if list_tokenbegin[j] == begin_index_temp:
  3754. begin_index = j
  3755. break
  3756. elif list_tokenbegin[j] > begin_index_temp:
  3757. begin_index = j - 1
  3758. break
  3759. index = servicetime['end_index']
  3760. end_index_temp = index
  3761. for j in range(begin_index, len(list_tokenbegin)):
  3762. if list_tokenbegin[j] >= index:
  3763. end_index = j - 1
  3764. break
  3765. entity_id = "%s_%d_%d_%d" % (doc_id, sentence_index, begin_index, end_index)
  3766. list_sentence_entitys.append(
  3767. Entity(doc_id, entity_id, entity_text, entity_type, sentence_index, begin_index, end_index,
  3768. begin_index_temp, end_index_temp,in_attachment=in_attachment, prob=servicetime["prob"]))
  3769. # 2021/12/29 新增比率提取
  3770. list_ratio = extract_ratio(sentence_text)
  3771. entity_type = "ratio"
  3772. for ratio in list_ratio:
  3773. # print("ratio", ratio)
  3774. begin_index_temp = ratio['begin_index']
  3775. for j in range(len(list_tokenbegin)):
  3776. if list_tokenbegin[j] == begin_index_temp:
  3777. begin_index = j
  3778. break
  3779. elif list_tokenbegin[j] > begin_index_temp:
  3780. begin_index = j - 1
  3781. break
  3782. index = ratio['end_index']
  3783. end_index_temp = index
  3784. for j in range(begin_index, len(list_tokenbegin)):
  3785. if list_tokenbegin[j] >= index:
  3786. end_index = j - 1
  3787. break
  3788. entity_id = "%s_%d_%d_%d" % (doc_id, sentence_index, begin_index, end_index)
  3789. entity_text = ratio['body']
  3790. ratio_value = (ratio['value'],ratio['type'])
  3791. _entity = Entity(doc_id, entity_id, entity_text, entity_type, sentence_index, begin_index, end_index,
  3792. begin_index_temp, end_index_temp,in_attachment=in_attachment)
  3793. _entity.ratio_value = ratio_value
  3794. list_sentence_entitys.append(_entity)
  3795. list_sentence_entitys.sort(key=lambda x:x.begin_index)
  3796. list_entitys_temp = list_entitys_temp+list_sentence_entitys
  3797. # 补充ner模型未识别全的company/org实体
  3798. for sentence_index in range(len(list_sentence)):
  3799. sentence_text = list_sentence[sentence_index].sentence_text
  3800. tokens = list_sentence[sentence_index].tokens
  3801. doc_id = list_sentence[sentence_index].doc_id
  3802. in_attachment = list_sentence[sentence_index].in_attachment
  3803. list_tokenbegin = []
  3804. begin = 0
  3805. for i in range(0, len(tokens)):
  3806. list_tokenbegin.append(begin)
  3807. begin += len(str(tokens[i]))
  3808. list_tokenbegin.append(begin + 1)
  3809. add_sentence_entitys = []
  3810. company_dict = sorted(list(company_dict),key=lambda x:len(x[1]),reverse=True)
  3811. for company_type,company_text in company_dict:
  3812. begin_index_list = findAllIndex(company_text,sentence_text)
  3813. for begin_index in begin_index_list:
  3814. is_continue = False
  3815. for t_begin,t_end in list(company_index[sentence_index]):
  3816. if begin_index>=t_begin and begin_index+len(company_text)<=t_end:
  3817. is_continue = True
  3818. break
  3819. if not is_continue:
  3820. add_sentence_entitys.append((begin_index,begin_index+len(company_text),company_type,company_text))
  3821. company_index[sentence_index].add((begin_index,begin_index+len(company_text)))
  3822. else:
  3823. continue
  3824. for ner_entity in add_sentence_entitys:
  3825. begin_index_temp = ner_entity[0]
  3826. end_index_temp = ner_entity[1]
  3827. entity_type = ner_entity[2]
  3828. entity_text = ner_entity[3]
  3829. if entity_type in ["org","company"] and not isLegalEnterprise(entity_text):
  3830. continue
  3831. for j in range(len(list_tokenbegin)):
  3832. if list_tokenbegin[j]==begin_index_temp:
  3833. begin_index = j
  3834. break
  3835. elif list_tokenbegin[j]>begin_index_temp:
  3836. begin_index = j-1
  3837. break
  3838. begin_index_temp += len(str(entity_text))
  3839. for j in range(begin_index,len(list_tokenbegin)):
  3840. if list_tokenbegin[j]>=begin_index_temp:
  3841. end_index = j-1
  3842. break
  3843. entity_id = "%s_%d_%d_%d"%(doc_id,sentence_index,begin_index,end_index)
  3844. if entity_type in ["org","company"] and entity_text in not_extract_roles: # 过滤掉名称在 需要过滤企业单位列表里的
  3845. continue
  3846. #去掉标点符号
  3847. entity_text = re.sub("[,,。:!&@$\*]","",entity_text)
  3848. entity_text = entity_text.replace("(","(").replace(")",")") if isinstance(entity_text,str) else entity_text
  3849. 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))
  3850. list_entitys_temp.sort(key=lambda x:(x.sentence_index,x.begin_index))
  3851. list_entitys.append(list_entitys_temp)
  3852. return list_entitys
  3853. def union_result(codeName,prem):
  3854. '''
  3855. @summary:模型的结果拼成字典
  3856. @param:
  3857. codeName:编号名称模型的结果字典
  3858. prem:拿到属性的角色的字典
  3859. @return:拼接起来的字典
  3860. '''
  3861. result = []
  3862. assert len(codeName)==len(prem)
  3863. for item_code,item_prem in zip(codeName,prem):
  3864. result.append(dict(item_code,**item_prem))
  3865. return result
  3866. def persistenceData(data):
  3867. '''
  3868. @summary:将中间结果保存到数据库-线上生产的时候不需要执行
  3869. '''
  3870. import psycopg2
  3871. conn = psycopg2.connect(dbname="BiddingKG",user="postgres",password="postgres",host="192.168.2.101")
  3872. cursor = conn.cursor()
  3873. for item_index in range(len(data)):
  3874. item = data[item_index]
  3875. doc_id = item[0]
  3876. dic = item[1]
  3877. code = dic['code']
  3878. name = dic['name']
  3879. prem = dic['prem']
  3880. if len(code)==0:
  3881. code_insert = ""
  3882. else:
  3883. code_insert = ";".join(code)
  3884. prem_insert = ""
  3885. for item in prem:
  3886. for x in item:
  3887. if isinstance(x, list):
  3888. if len(x)>0:
  3889. for x1 in x:
  3890. prem_insert+="/".join(x1)+","
  3891. prem_insert+="$"
  3892. else:
  3893. prem_insert+=str(x)+"$"
  3894. prem_insert+=";"
  3895. sql = " insert into predict_validation(doc_id,code,name,prem) values('"+doc_id+"','"+code_insert+"','"+name+"','"+prem_insert+"')"
  3896. cursor.execute(sql)
  3897. conn.commit()
  3898. conn.close()
  3899. def persistenceData1(list_entitys,list_sentences):
  3900. '''
  3901. @summary:将中间结果保存到数据库-线上生产的时候不需要执行
  3902. '''
  3903. import psycopg2
  3904. conn = psycopg2.connect(dbname="BiddingKG",user="postgres",password="postgres",host="192.168.2.101")
  3905. cursor = conn.cursor()
  3906. for list_entity in list_entitys:
  3907. for entity in list_entity:
  3908. if entity.values is not None:
  3909. 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)+")"
  3910. else:
  3911. 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)+")"
  3912. cursor.execute(sql)
  3913. for list_sentence in list_sentences:
  3914. for sentence in list_sentence:
  3915. str_tokens = "["
  3916. for item in sentence.tokens:
  3917. str_tokens += "'"
  3918. if item=="'":
  3919. str_tokens += "''"
  3920. else:
  3921. str_tokens += item
  3922. str_tokens += "',"
  3923. str_tokens = str_tokens[:-1]+"]"
  3924. sql = " insert into predict_sentences(doc_id,sentence_index,tokens) values('"+sentence.doc_id+"',"+str(sentence.sentence_index)+",array"+str_tokens+")"
  3925. cursor.execute(sql)
  3926. conn.commit()
  3927. conn.close()
  3928. def _handle(item,result_queue):
  3929. dochtml = item["dochtml"]
  3930. docid = item["docid"]
  3931. list_innerTable = tableToText(BeautifulSoup(dochtml,"lxml"))
  3932. flag = False
  3933. if list_innerTable:
  3934. flag = True
  3935. for table in list_innerTable:
  3936. result_queue.put({"docid":docid,"json_table":json.dumps(table,ensure_ascii=False)})
  3937. def getPredictTable():
  3938. filename = "D:\Workspace2016\DataExport\data\websouce_doc.csv"
  3939. import pandas as pd
  3940. import json
  3941. from BiddingKG.dl.common.MultiHandler import MultiHandler,Queue
  3942. df = pd.read_csv(filename)
  3943. df_data = {"json_table":[],"docid":[]}
  3944. _count = 0
  3945. _sum = len(df["docid"])
  3946. task_queue = Queue()
  3947. result_queue = Queue()
  3948. _index = 0
  3949. for dochtml,docid in zip(df["dochtmlcon"],df["docid"]):
  3950. task_queue.put({"docid":docid,"dochtml":dochtml,"json_table":None})
  3951. _index += 1
  3952. mh = MultiHandler(task_queue=task_queue,task_handler=_handle,result_queue=result_queue,process_count=5,thread_count=1)
  3953. mh.run()
  3954. while True:
  3955. try:
  3956. item = result_queue.get(block=True,timeout=1)
  3957. df_data["docid"].append(item["docid"])
  3958. df_data["json_table"].append(item["json_table"])
  3959. except Exception as e:
  3960. print(e)
  3961. break
  3962. df_1 = pd.DataFrame(df_data)
  3963. df_1.to_csv("../form/websource_67000_table.csv",columns=["docid","json_table"])
  3964. if __name__=="__main__":
  3965. '''
  3966. import glob
  3967. for file in glob.glob("C:\\Users\\User\\Desktop\\test\\*.html"):
  3968. file_txt = str(file).replace("html","txt")
  3969. with codecs.open(file_txt,"a+",encoding="utf8") as f:
  3970. f.write("\n================\n")
  3971. content = codecs.open(file,"r",encoding="utf8").read()
  3972. f.write(segment(tableToText(BeautifulSoup(content,"lxml"))))
  3973. '''
  3974. # content = codecs.open("C:\\Users\\User\\Desktop\\2.html","r",encoding="utf8").read()
  3975. # print(segment(tableToText(BeautifulSoup(content,"lxml"))))
  3976. # getPredictTable()
  3977. text = '是否拟中标人:是,评标排名:1,价格类型:(万元)报价:13311.1582,得分:84.46,项目负责人:邓焱文'
  3978. text = ',采购包1:采购包预算金额(元:1,500000.00,采购包最高限价(元:1,430600.00,'
  3979. text = '成交人:中坤电力有限公司,成交价格:11493,603.52元,质量:合格,项目工期:117天,'
  3980. text = '3年投标报价(元)含税 6299700.00'
  3981. # text = '数量及单位1:65台,单价2:800,投标报价3=1×2:52000。'
  3982. print(get_money_entity(text, found_yeji=0))
  3983. # with open('D:/138786703.html', 'r', encoding='utf-8') as f:
  3984. # sourceContent = f.read()
  3985. # # article_processed = segment(tableToText(BeautifulSoup(sourceContent, "lxml")))
  3986. # # print(article_processed)
  3987. #
  3988. # list_articles, list_sentences, list_entitys, _cost_time = get_preprocessed([['doc_id', sourceContent, "", "", '', '2021-02-01']], useselffool=True)
  3989. # for entity in list_entitys[0]:
  3990. # print(entity.entity_type, entity.entity_text)