Preprocessing.py 210 KB

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