Preprocessing.py 220 KB

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