Preprocessing.py 206 KB

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