Preprocessing.py 210 KB

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