12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304 |
- # -*- coding: utf-8 -*-
- from bs4 import BeautifulSoup, Comment
- import copy
- import sys
- import os
- import time
- import codecs
- from BiddingKG.dl.ratio.re_ratio import extract_ratio
- from BiddingKG.dl.table_head.predict_torch import predict
- sys.setrecursionlimit(1000000)
- sys.path.append(os.path.abspath("../.."))
- sys.path.append(os.path.abspath(".."))
- from BiddingKG.dl.common.Utils import *
- from BiddingKG.dl.interface.Entitys import *
- from BiddingKG.dl.interface.predictor import getPredictor, TableTag2List
- from BiddingKG.dl.common.nerUtils import *
- from BiddingKG.dl.money.moneySource.ruleExtra import extract_moneySource
- from BiddingKG.dl.time.re_servicetime import extract_servicetime
- from BiddingKG.dl.relation_extraction.re_email import extract_email
- from BiddingKG.dl.bidway.re_bidway import extract_bidway,bidway_integrate
- from BiddingKG.dl.fingerprint.documentFingerprint import getFingerprint
- from BiddingKG.dl.entityLink.entityLink import *
- #
- def tableToText(soup, docid=None, return_kv=False):
- '''
- @param:
- soup:网页html的soup
- @return:处理完表格信息的网页text
- '''
-
- def getTrs(tbody):
- #获取所有的tr
- trs = []
- objs = tbody.find_all(recursive=False)
- for obj in objs:
- if obj.name=="tr":
- trs.append(obj)
- if obj.name=="tbody":
- for tr in obj.find_all("tr",recursive=False):
- trs.append(tr)
- return trs
- def fixSpan(tbody):
- # 处理colspan, rowspan信息补全问题
- #trs = tbody.findChildren('tr', recursive=False)
- trs = getTrs(tbody)
- ths_len = 0
- ths = list()
- trs_set = set()
- #修改为先进行列补全再进行行补全,否则可能会出现表格解析混乱
- # 遍历每一个tr
- for indtr, tr in enumerate(trs):
- ths_tmp = tr.findChildren('th', recursive=False)
- #不补全含有表格的tr
- if len(tr.findChildren('table'))>0:
- continue
- if len(ths_tmp) > 0:
- ths_len = ths_len + len(ths_tmp)
- for th in ths_tmp:
- ths.append(th)
- trs_set.add(tr)
- # 遍历每行中的element
- tds = tr.findChildren(recursive=False)
- for indtd, td in enumerate(tds):
- # 若有colspan 则补全同一行下一个位置
- if 'colspan' in td.attrs:
- if str(re.sub("[^0-9]","",str(td['colspan'])))!="":
- col = int(re.sub("[^0-9]","",str(td['colspan'])))
- if col<100 and len(td.get_text())<1000:
- td['colspan'] = 1
- for i in range(1, col, 1):
- td.insert_after(copy.copy(td))
- for indtr, tr in enumerate(trs):
- ths_tmp = tr.findChildren('th', recursive=False)
- #不补全含有表格的tr
- if len(tr.findChildren('table'))>0:
- continue
- if len(ths_tmp) > 0:
- ths_len = ths_len + len(ths_tmp)
- for th in ths_tmp:
- ths.append(th)
- trs_set.add(tr)
- # 遍历每行中的element
- tds = tr.findChildren(recursive=False)
- for indtd, td in enumerate(tds):
- # 若有rowspan 则补全下一行同样位置
- if 'rowspan' in td.attrs:
- if str(re.sub("[^0-9]","",str(td['rowspan'])))!="":
- row = int(re.sub("[^0-9]","",str(td['rowspan'])))
- td['rowspan'] = 1
- for i in range(1, row, 1):
- # 获取下一行的所有td, 在对应的位置插入
- if indtr+i<len(trs):
- tds1 = trs[indtr + i].findChildren(['td','th'], recursive=False)
- if len(tds1) >= (indtd) and len(tds1)>0:
- if indtd > 0:
- tds1[indtd - 1].insert_after(copy.copy(td))
- else:
- tds1[0].insert_before(copy.copy(td))
- elif indtd-2>0 and len(tds1) > 0 and len(tds1) == indtd - 1: # 修正某些表格最后一列没补全
- tds1[indtd-2].insert_after(copy.copy(td))
- def getTable(tbody):
- #trs = tbody.findChildren('tr', recursive=False)
- trs = getTrs(tbody)
- inner_table = []
- for tr in trs:
- tr_line = []
- tds = tr.findChildren(['td','th'], recursive=False)
- if len(tds)==0:
- if return_kv:
- tr_line.append([re.sub('\xa0','',tr.get_text()),0])
- else:
- tr_line.append([re.sub('\xa0','',segment(tr,final=False)),0]) # 2021/12/21 修复部分表格没有td 造成数据丢失
- for td in tds:
- if return_kv:
- tr_line.append([re.sub('\xa0','',td.get_text()),0])
- else:
- tr_line.append([re.sub('\xa0','',segment(td,final=False)),0])
- #tr_line.append([td.get_text(),0])
- inner_table.append(tr_line)
- return inner_table
-
- #处理表格不对齐的问题
- def fixTable(inner_table,fix_value="~~"):
- maxWidth = 0
- for item in inner_table:
- if len(item)>maxWidth:
- maxWidth = len(item)
- if maxWidth > 100:
- # log('表格列数大于100,表格异常不做处理。')
- return []
- for i in range(len(inner_table)):
- if len(inner_table[i])<maxWidth:
- for j in range(maxWidth-len(inner_table[i])):
- inner_table[i].append([fix_value,0])
- return inner_table
-
- def removePadding(inner_table,pad_row = "@@",pad_col = "##"):
- height = len(inner_table)
- width = len(inner_table[0])
- for i in range(height):
- point = ""
- for j in range(width):
- if inner_table[i][j][0]==point and point!="":
- inner_table[i][j][0] = pad_row
- else:
- if inner_table[i][j][0] not in [pad_row,pad_col]:
- point = inner_table[i][j][0]
- for j in range(width):
- point = ""
- for i in range(height):
- if inner_table[i][j][0]==point and point!="":
- inner_table[i][j][0] = pad_col
- else:
- if inner_table[i][j][0] not in [pad_row,pad_col]:
- point = inner_table[i][j][0]
-
- def addPadding(inner_table,pad_row = "@@",pad_col = "##"):
- height = len(inner_table)
- width = len(inner_table[0])
- for i in range(height):
- for j in range(width):
- if inner_table[i][j][0]==pad_row:
- inner_table[i][j][0] = inner_table[i][j-1][0]
- inner_table[i][j][1] = inner_table[i][j-1][1]
- if inner_table[i][j][0]==pad_col:
- inner_table[i][j][0] = inner_table[i-1][j][0]
- inner_table[i][j][1] = inner_table[i-1][j][1]
- def repairTable(inner_table, dye_set=set(), key_set=set(), fix_value="~~"):
- """
- @summary: 修复表头识别,将明显错误的进行修正
- """
- def repairNeeded(line):
- first_1 = -1
- last_1 = -1
- first_0 = -1
- last_0 = -1
- count_1 = 0
- count_0 = 0
- for i in range(len(line)):
- if line[i][0] == fix_value:
- continue
- if line[i][1]==1:
- if first_1==-1:
- first_1 = i
- last_1 = i
- count_1 += 1
- if line[i][1]==0:
- if first_0 == -1:
- first_0 = i
- last_0 = i
- count_0 += 1
- if first_1 ==-1 or last_0 == -1:
- return False
- # 异常情况:第一个不是表头;最后一个是表头;表头个数远大于属性值个数
- if first_1-0 > 0 or last_0-len(line)+1 < 0 or last_1 == len(line)-1 or count_1-count_0 >= 3:
- return True
- return False
- def getsimilarity(line, line1):
- same_count = 0
- for item, item1 in zip(line,line1):
- if item[1] == item1[1]:
- same_count += 1
- return same_count/len(line)
- def selfrepair(inner_table,index,dye_set,key_set):
- """
- @summary: 计算每个节点受到的挤压度来判断是否需要染色
- """
- # print("B",inner_table[index])
- min_presure = 3
- list_dye = []
- first = None
- count = 0
- # temp_set = set()
- temp_set = set(['~~']) # 2023/10/10纠正236239652 受让单位识别不到表头; 受让单位,明细用途:用途名称:陵川县民政局,
- _index = 0
- for item in inner_table[index]:
- if first is None:
- first = item[1]
- if item[0] not in temp_set:
- count += 1
- temp_set.add(item[0])
- else:
- if first == item[1]:
- if item[0] not in temp_set:
- temp_set.add(item[0])
- count += 1
- else:
- list_dye.append([first,count,_index])
- first = item[1]
- temp_set.add(item[0])
- count = 1
- _index += 1
- list_dye.append([first,count,_index])
- if len(list_dye)>1:
- begin = 0
- end = 0
- for i in range(len(list_dye)):
- end = list_dye[i][2]
- dye_flag = False
- # 首尾要求压力减一
- if i==0:
- if list_dye[i+1][1]-list_dye[i][1]+1>=min_presure-1:
- dye_flag = True
- dye_type = list_dye[i+1][0]
- elif i==len(list_dye)-1:
- if list_dye[i-1][1]-list_dye[i][1]+1>=min_presure-1:
- dye_flag = True
- dye_type = list_dye[i-1][0]
- else:
- if list_dye[i][1]>1:
- if list_dye[i+1][1]-list_dye[i][1]+1>=min_presure:
- dye_flag = True
- dye_type = list_dye[i+1][0]
- if list_dye[i-1][1]-list_dye[i][1]+1>=min_presure:
- dye_flag = True
- dye_type = list_dye[i-1][0]
- else:
- if list_dye[i+1][1]+list_dye[i-1][1]-list_dye[i][1]+1>=min_presure:
- dye_flag = True
- dye_type = list_dye[i+1][0]
- if list_dye[i+1][1]+list_dye[i-1][1]-list_dye[i][1]+1>=min_presure:
- dye_flag = True
- dye_type = list_dye[i-1][0]
- if dye_flag:
- for h in range(begin,end):
- inner_table[index][h][1] = dye_type
- dye_set.add((inner_table[index][h][0],dye_type))
- key_set.add(inner_table[index][h][0])
- begin = end
- # print("E",inner_table[index])
- def otherrepair(inner_table,index,dye_set,key_set):
- list_provide_repair = []
- if index==0 and len(inner_table)>1:
- list_provide_repair.append(index+1)
- elif index==len(inner_table)-1:
- list_provide_repair.append(index-1)
- else:
- list_provide_repair.append(index+1)
- list_provide_repair.append(index-1)
- for provide_index in list_provide_repair:
- if not repairNeeded(inner_table[provide_index]):
- same_prob = getsimilarity(inner_table[index], inner_table[provide_index])
- if same_prob>=0.8:
- for i in range(len(inner_table[provide_index])):
- if inner_table[index][i][1]!=inner_table[provide_index][i][1]:
- dye_set.add((inner_table[index][i][0],inner_table[provide_index][i][1]))
- key_set.add(inner_table[index][i][0])
- inner_table[index][i][1] = inner_table[provide_index][i][1]
- elif same_prob<=0.2:
- for i in range(len(inner_table[provide_index])):
- if inner_table[index][i][1]==inner_table[provide_index][i][1]:
- dye_set.add((inner_table[index][i][0],inner_table[provide_index][i][1]))
- key_set.add(inner_table[index][i][0])
- inner_table[index][i][1] = 0 if inner_table[provide_index][i][1] ==1 else 1
- len_dye_set = len(dye_set)
- height = len(inner_table)
- for i in range(height):
- if repairNeeded(inner_table[i]):
- selfrepair(inner_table, i, dye_set, key_set)
- #otherrepair(inner_table,i,dye_set,key_set)
- for h in range(len(inner_table)):
- for w in range(len(inner_table[0])):
- if inner_table[h][w][0] in key_set:
- for item in dye_set:
- if inner_table[h][w][0] == item[0]:
- inner_table[h][w][1] = item[1]
- # 如果两个set长度不相同,则有同一个key被反复染色,将导致无限迭代
- if len(dye_set) != len(key_set):
- for i in range(height):
- if repairNeeded(inner_table[i]):
- selfrepair(inner_table,i,dye_set,key_set)
- #otherrepair(inner_table,i,dye_set,key_set)
- return
- if len(dye_set) == len_dye_set:
- '''
- for i in range(height):
- if repairNeeded(inner_table[i]):
- otherrepair(inner_table,i,dye_set,key_set)
- '''
- return
- repairTable(inner_table, dye_set, key_set)
- def repair_table2(inner_table, show=0, row_no=0):
- """
- @summary: 修复表头识别,将明显错误的进行修正
- """
- # 循环处理单元格,一次获取需要的
- one_head_index_list = []
- zero_head_index_list = []
- all_head_index_list = []
- for i in range(len(inner_table)):
- head_cnt = 0
- for j in range(len(inner_table[i])):
- # 删除前后逗号
- inner_table[i][j][0] = re.sub('^[,,]+', '', inner_table[i][j][0])
- inner_table[i][j][0] = re.sub('[,,]+$', '', inner_table[i][j][0])
- # 统计表头数
- if inner_table[i][j][1] == 1:
- head_cnt += 1
- # 表头数list
- if head_cnt == 0:
- zero_head_index_list.append(i)
- elif head_cnt == 1:
- one_head_index_list.append(i)
- elif head_cnt == len(inner_table[i]):
- all_head_index_list.append(i)
- # 修复冒号在文本中间的,不能作为表头;(冒号后面需多个字)
- # 冒号在括号中的除外
- # 冒号在最后的,判断后一个格子是否有重复的文字
- for i in range(len(inner_table)):
- for j in range(len(inner_table[i])):
- _text = inner_table[i][j][0]
- if len(_text) >= 3 and inner_table[i][j][1] == 1:
- match = re.search('[::]', _text)
- if match:
- start_index, end_index = match.span()
- if start_index == 0:
- continue
- if end_index == len(_text):
- 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):
- inner_table[i][j][1] = 0
- inner_table[i][j+1][1] = 0
- else:
- continue
- if re.search('[((]', _text[:start_index]) and re.search('[))]', _text[end_index:]):
- continue
- m1 = re.search('[\u4e00-\u9fa50-9a-zA-Z]', _text[:start_index])
- m2 = re.search('[\u4e00-\u9fa50-9a-zA-Z]', _text[end_index:])
- if m1 and m2 and (len(m2.group()) >= 2 or m2.group() in ['是', '否']):
- inner_table[i][j][1] = 0
- if show:
- print('inner_table[i]1', inner_table[row_no])
- # 修复实际只有几列,但有一列由于重复占了太多行表头识别错误
- # for i in range(len(inner_table)):
- # head_flag_dict = {}
- # for j in range(len(inner_table[i])):
- # if inner_table[i][j][0] in head_flag_dict.keys():
- # head_flag_dict[inner_table[i][j][0]] += [inner_table[i][j][1]]
- # else:
- # head_flag_dict[inner_table[i][j][0]] = [inner_table[i][j][1]]
- #
- # if len(head_flag_dict.keys()) == 2:
- # col_flag = None
- # col_value = None
- # for key in head_flag_dict.keys():
- # flag_list = head_flag_dict[key]
- # if len(flag_list) >= 4 and len(set(flag_list)) == 2 and len(set(flag_list[1:])) == 1:
- # col_flag = flag_list[0]
- # col_value = key
- # break
- #
- # if col_flag is not None:
- # for j in range(len(inner_table[i])):
- # if inner_table[i][j][0] == col_value:
- # inner_table[i][j][1] = col_flag
- # 多个重复列的预测值不同,以第一个为准
- for i in range(len(inner_table)):
- col = inner_table[i][0]
- for j in range(len(inner_table[i])):
- if inner_table[i][j][0] == col[0]:
- if inner_table[i][j][1] != col[1]:
- inner_table[i][j][1] = col[1]
- else:
- col = inner_table[i][j]
- if show:
- print('inner_table[i]2', inner_table[row_no])
- # 修复多个重复的单元格表头不一致
- # for i in range(len(inner_table)):
- # for j in range(len(inner_table[i])-1):
- # only_chinese1 = ''.join(re.findall('[\u4e00-\u9fa5]+', inner_table[i][j][0]))
- # only_chinese2 = ''.join(re.findall('[\u4e00-\u9fa5]+', inner_table[i][j+1][0]))
- # if only_chinese1 == only_chinese2 and inner_table[i][j][1] != inner_table[i][j+1][1]:
- # inner_table[i][j][1] = 1
- # inner_table[i][j+1][1] = 1
- # if show:
- # print('inner_table[i]3', inner_table[row_no])
- # # 修复一行几乎都是表头,个别不是;或者一行几乎都是非表头,个别是
- # for i in range(len(inner_table)):
- # head_dict = {}
- # not_head_dict = {}
- # for j in range(len(inner_table[i])):
- # if inner_table[i][j][1] == 1:
- # if inner_table[i][j][0] not in head_dict:
- # head_dict[inner_table[i][j][0]] = 1
- # else:
- # if inner_table[i][j][0] not in not_head_dict:
- # not_head_dict[inner_table[i][j][0]] = 1
- #
- # # 非表头:表头 <= 1:3
- # # if len(head_dict.keys()) > 0 and len(not_head_dict.keys()) / len(head_dict.keys()) <= 1/3 and len(head_dict.keys()) >= 3:
- # # for j in range(len(inner_table[i])):
- # # if len(re.sub(' ', '', inner_table[i][j][0])) > 0:
- # # inner_table[i][j][1] = 1
- #
- # # 表头数一个且非表头数大于2且上一行都是表头
- # if i > 0 and len(head_dict.keys()) == 1 and len(not_head_dict.keys()) >= 2 and inner_table[i][0][1] == 0:
- # last_row = inner_table[i-1]
- # col_list = []
- # for j in range(len(last_row)):
- # if len(re.sub(' ', '', last_row[j][0])) > 0:
- # if last_row[j][1] == 0:
- # col_list = []
- # break
- # col_list.append(last_row[j][0])
- # if col_list:
- # col_list = list(set(col_list))
- # if len(col_list) > 2:
- # for j in range(len(inner_table[i])):
- # if inner_table[i][j][1] == 1:
- # inner_table[i][j][1] = 0
- # 一整个大表格,第一行为表头,下面行中有个别格子被识别为表头
- # 候选人后面修复
- for index in one_head_index_list:
- if (index - 1 in zero_head_index_list and index - 2 in zero_head_index_list) \
- or (index - 1 in zero_head_index_list and index - 2 in all_head_index_list) \
- or (index - 1 in all_head_index_list):
- for j in range(len(inner_table[index])):
- inner_table[index][j][1] = 0
- zero_head_index_list.append(index)
- if show:
- print('inner_table[i]4', inner_table[row_no])
- # 修复第一第二第三中标候选人作为表头
- first_tenderer = ['第一中标候选人', '第一中标人', '第一中标(成交)人', '第一候选人']
- second_tenderer = ['第二中标候选人', '第二中标(成交)候选人', '第二候选人']
- third_tenderer = ['第三中标候选人', '第三中标(成交)候选人', '第三候选人']
- # n1 next one, n2 next two, l1 last one, l2 last two
- for i in range(len(inner_table)):
- row = inner_table[i]
- n1_row, n2_row = None, None
- if i+1 < len(inner_table):
- n1_row = inner_table[i+1]
- if i+2 < len(inner_table):
- n2_row = inner_table[i+2]
- for j in range(len(row)):
- row_col = row[j]
- n1_row_col, n2_row_col = None, None
- row_n1_col, row_n2_col = None, None
- n1_row_n1_col, n2_row_n1_col, n1_row_n2_col = None, None, None
- if n1_row:
- n1_row_col = n1_row[j]
- if n2_row:
- n2_row_col = n2_row[j]
- if j+1 < len(row):
- row_n1_col = row[j+1]
- if j+2 < len(row):
- row_n2_col = row[j+2]
- if n1_row and j+1 < len(n1_row):
- n1_row_n1_col = n1_row[j+1]
- if n2_row and j+1 < len(n2_row):
- n2_row_n1_col = n2_row[j+1]
- if n1_row and j+2 < len(n1_row):
- n1_row_n2_col = n1_row[j+2]
- # 连续作为行表头
- if row_col[0] in first_tenderer and row_n1_col and row_n1_col[1] == 0:
- if n1_row_col and n1_row_col[0] in second_tenderer and n1_row_n1_col and n1_row_n1_col[1] == 0:
- inner_table[i][j][1] = 1
- inner_table[i+1][j][1] = 1
- if n2_row_col and n2_row_col[0] in third_tenderer and n2_row_n1_col and n2_row_n1_col[1] == 0:
- inner_table[i+2][j][1] = 1
- # 连续作为列表头
- if row_col[0] in first_tenderer and n1_row_col and n1_row_col[1] == 0:
- if row_n1_col and row_n1_col[0] in second_tenderer and n1_row_n1_col and n1_row_n1_col[1] == 0:
- inner_table[i][j][1] = 1
- inner_table[i][j+1][1] = 1
- if row_n2_col and row_n2_col[0] in third_tenderer and n1_row_n2_col and n1_row_n2_col[1] == 0:
- inner_table[i][j+2][1] = 1
- if show:
- print('inner_table[i]5', inner_table[row_no])
- # 修复表头关键词未作为表头
- # 文本匹配关键词,直接作为表头
- head_keyword = ['供应商', '总价']
- # 末尾匹配关键词且前一列为表头且与前一列文本不同,直接不做表头
- head_keyword2 = ['管理中心', '有限公司', '项目采购', ]
- # 开头匹配关键词,直接不做表头
- head_keyword3 = ['详见', '选定', '咨询服务', '标准物资', '电汇', '承兑']
- # 文本匹配关键词且前一列为表头,直接作为表头
- head_keyword4 = ['综合排名']
- # 文本在关键词中,直接不做表头
- head_keyword5 = ['殡葬用地']
- # n1 next one, n2 next two, l1 last one, l2 last two
- for i in range(len(inner_table)):
- row = inner_table[i]
- for j in range(len(row)):
- row_col = row[j]
- row_l1_col = None
- if j-1 > 0:
- row_l1_col = row[j-1]
- match = re.search('[\u4e00-\u9fa50-9a-zA-Z::]+', row_col[0])
- if inner_table[i][j][1] == 0 and match and match.group() in head_keyword:
- inner_table[i][j][1] = 1
- for key in head_keyword2:
- match = re.search(key+'$', row_col[0])
- 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:
- inner_table[i][j][1] = 0
- for key in head_keyword3:
- match = re.search('^'+key, row_col[0])
- if match and row_col[1] == 1:
- inner_table[i][j][1] = 0
- for key in head_keyword4:
- match = re.search(key, row_col[0])
- if j > 0 and row_l1_col and row_l1_col[1] == 1 and match and row_col[1] == 0:
- inner_table[i][j][1] = 1
- if row_col[0] in head_keyword5:
- inner_table[i][j][1] = 0
- if show:
- print('inner_table[i]6', inner_table[row_no])
- # 修复姓名被作为表头 # 2023-02-10 取消修复,避免项目名称、编号,单位、单价等作为了非表头
- # surname = [
- # "赵", "钱", "孙", "李", "周", "吴", "郑", "王", "冯", "陈", "褚", "卫", "蒋", "沈", "韩", "杨", "朱", "秦", "尤", "许", "何", "吕", "施", "张", "孔", "曹", "严", "华", "金", "魏", "陶", "姜", "戚", "谢", "邹", "喻", "柏", "水", "窦", "章", "云", "苏", "潘", "葛", "奚", "范", "彭", "郎", "鲁", "韦", "昌", "马", "苗", "凤", "花", "方", "俞", "任", "袁", "柳", "酆", "鲍", "史", "唐", "费", "廉", "岑", "薛", "雷", "贺", "倪", "汤", "滕", "殷", "罗", "毕", "郝", "邬", "安", "常", "乐", "于", "时", "傅", "皮", "卞", "齐", "康", "伍", "余", "元", "卜", "顾", "孟", "平", "黄", "和", "穆", "萧", "尹", "姚", "邵", "湛", "汪", "祁", "毛", "禹", "狄", "米", "贝", "明", "臧", "计", "伏", "成", "戴", "谈", "宋", "茅", "庞", "熊", "纪", "舒", "屈", "项", "祝", "董", "梁", "杜", "阮", "蓝", "闵", "席", "季", "麻", "强", "贾", "路", "娄", "危", "江", "童", "颜", "郭", "梅", "盛", "林", "刁", "钟", "徐", "邱", "骆", "高", "夏", "蔡", "田", "樊", "胡", "凌", "霍", "虞", "万", "支", "柯", "昝", "管", "卢", "莫", "经", "房", "裘", "缪", "干", "解", "应", "宗", "丁", "宣", "贲", "邓", "郁", "单", "杭", "洪", "包", "诸", "左", "石", "崔", "吉", "钮", "龚", "程", "嵇", "邢", "滑", "裴", "陆", "荣", "翁", "荀", "羊", "於", "惠", "甄", "麴", "家", "封", "芮", "羿", "储", "靳", "汲", "邴", "糜", "松", "井", "段", "富", "巫", "乌", "焦", "巴", "弓", "牧", "隗", "山", "谷", "车", "侯", "宓", "蓬", "全", "郗", "班", "仰", "秋", "仲", "伊", "宫", "宁", "仇", "栾", "暴", "甘", "钭", "厉", "戎", "祖", "武", "符", "刘", "景", "詹", "束", "龙", "叶", "幸", "司", "韶", "郜", "黎", "蓟", "薄", "印", "宿", "白", "怀", "蒲", "邰", "从", "鄂", "索", "咸", "籍", "赖", "卓", "蔺", "屠", "蒙", "池", "乔", "阴", "欎", "胥", "能", "苍", "双", "闻", "莘", "党", "翟", "谭", "贡", "劳", "逄", "姬", "申", "扶", "堵", "冉", "宰", "郦", "雍", "舄", "璩", "桑", "桂", "濮", "牛", "寿", "通", "边", "扈", "燕", "冀", "郏", "浦", "尚", "农", "温", "别", "庄", "晏", "柴", "瞿", "阎", "充", "慕", "连", "茹", "习", "宦", "艾", "鱼", "容", "向", "古", "易", "慎", "戈", "廖", "庾", "终", "暨", "居", "衡", "步", "都", "耿", "满", "弘", "匡", "国", "文", "寇", "广", "禄", "阙", "东", "殴", "殳", "沃", "利", "蔚", "越", "夔", "隆", "师", "巩", "厍", "聂", "晁", "勾", "敖", "融", "冷", "訾", "辛", "阚", "那", "简", "饶", "空", "曾", "毋", "沙", "乜", "养", "鞠", "须", "丰", "巢", "关", "蒯", "相", "查", "後", "荆", "红", "游", "竺", "权", "逯", "盖", "益", "桓", "公", "万俟", "司马", "上官", "欧阳", "夏侯", "诸葛", "闻人", "东方", "赫连", "皇甫", "尉迟", "公羊", "澹台", "公冶", "宗政", "濮阳", "淳于", "单于", "太叔", "申屠", "公孙", "仲孙", "轩辕", "令狐", "钟离", "宇文", "长孙", "慕容", "鲜于", "闾丘", "司徒", "司空", "亓官", "司寇", "仉", "督", "子车", "颛孙", "端木", "巫马", "公西", "漆雕", "乐正", "壤驷", "公良", "拓跋", "夹谷", "宰父", "谷梁", "晋", "楚", "闫", "法", "汝", "鄢", "涂", "钦", "段干", "百里", "东郭", "南门", "呼延", "归", "海", "羊舌", "微生", "岳", "帅", "缑", "亢", "况", "后", "有", "琴", "梁丘", "左丘", "东门", "西门", "商", "牟", "佘", "佴", "伯", "赏", "南宫", "墨", "哈", "谯", "笪", "年", "爱", "阳", "佟", "第五", "言", "福",
- # ]
- # for i in range(len(inner_table)):
- # for j in range(len(inner_table[i])):
- # if inner_table[i][j][1] == 1 \
- # and 2 <= len(inner_table[i][j][0]) <= 4 \
- # and (inner_table[i][j][0][0] in surname or inner_table[i][j][0][:2] in surname) \
- # and re.search("[^\u4e00-\u9fa5]", inner_table[i][j][0]) is None:
- # inner_table[i][j][1] = 0
- return inner_table
- def sliceTable(inner_table,fix_value="~~"):
- #进行分块
- height = len(inner_table)
- width = len(inner_table[0])
- head_list = []
- head_list.append(0)
- last_head = None
- last_is_same_value = False
- for h in range(height):
- is_all_key = True#是否是全表头行
- is_all_value = True#是否是全属性值
- is_same_with_lastHead = True#和上一行的结构是否相同
- is_same_value=True#一行的item都一样
- #is_same_first_item = True#与上一行的第一项是否相同
- same_value = inner_table[h][0][0]
- for w in range(width):
- if last_head is not None:
- if inner_table[h-1][w][0] != fix_value and inner_table[h-1][w][0] != "" and inner_table[h-1][w][1] == 0:
- is_all_key = False
- if inner_table[h][w][0]==1:
- is_all_value = False
- if inner_table[h][w][1]!= inner_table[h-1][w][1]:
- is_same_with_lastHead = False
- if inner_table[h][w][0]!=fix_value and inner_table[h][w][0]!=same_value:
- is_same_value = False
- else:
- if re.search("\d+",same_value) is not None:
- is_same_value = False
- if h>0 and inner_table[h][0][0]!=inner_table[h-1][0][0]:
- is_same_first_item = False
- last_head = h
- if last_is_same_value:
- last_is_same_value = is_same_value
- continue
- if is_same_value:
- # 该块只有表头一行不合法
- if h - head_list[-1] > 1:
- head_list.append(h)
- last_is_same_value = is_same_value
- continue
- if not is_all_key:
- if not is_same_with_lastHead:
- # 该块只有表头一行不合法
- if h - head_list[-1] > 1:
- head_list.append(h)
- head_list.append(height)
- return head_list
-
- def setHead_initem(inner_table,pat_head,fix_value="~~",prob_min=0.5):
- set_item = set()
- height = len(inner_table)
- width = len(inner_table[0])
- empty_set = set()
- for i in range(height):
- for j in range(width):
- item = inner_table[i][j][0]
- if item.strip()=="":
- empty_set.add(item)
- else:
- set_item.add(item)
- list_item = list(set_item)
- if list_item:
- x = []
- for item in list_item:
- x.append(getPredictor("form").encode(item))
- predict_y = getPredictor("form").predict(np.array(x),type="item")
- _dict = dict()
- for item,values in zip(list_item,list(predict_y)):
- _dict[item] = values[1]
- # print("##",item,values)
- #print(_dict)
- for i in range(height):
- for j in range(width):
- item = inner_table[i][j][0]
- if item not in empty_set:
- 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)
- # print("=====")
- # for item in inner_table:
- # print(item)
- # print("======")
- repairTable(inner_table)
- head_list = sliceTable(inner_table)
-
- return inner_table,head_list
- def set_head_model(inner_table, show=0):
- origin_inner_table = copy.deepcopy(inner_table)
- for i in range(len(inner_table)):
- for j in range(len(inner_table[i])):
- # 删掉单格前后符号,以免影响表头预测
- col = inner_table[i][j][0]
- col = re.sub("^[^\u4e00-\u9fa5a-zA-Z0-9]+", "", col)
- col = re.sub("[^\u4e00-\u9fa5a-zA-Z0-9]+$", "", col)
- inner_table[i][j] = col
- # 模型预测表头
- # predict_list = predict(inner_table)
- start_time = time.time()
- predict_list = predict(inner_table)
- # print('table head predict cost: ', time.time()-start_time)
- # 组合结果
- for i in range(len(inner_table)):
- for j in range(len(inner_table[i])):
- inner_table[i][j] = [origin_inner_table[i][j][0], int(predict_list[i][j])]
- if origin_inner_table[i][j][0] in ['主要环境影响及预防或者减轻不良环境影响的对策和措施', '建设单位或地方政府作出的相关环保承诺', '公众反馈意见的联系方式'] and predict_list[i][j]!=1:
- inner_table[i][j] = [origin_inner_table[i][j][0], 1]
- elif origin_inner_table[i][j][0] in ['经评审的最低评标价法'] and predict_list[i][j]==1:
- inner_table[i][j] = [origin_inner_table[i][j][0], 0]
- if show:
- print(json.dumps(inner_table, ensure_ascii=False))
- print("="*80)
- print("table_head before repair")
- for r in inner_table:
- print('row', r)
- print("="*80)
- # 表头修正
- # repairTable(inner_table)
- inner_table = table_head_repair_process(inner_table, docid)
- # 组合结果
- for i in range(len(inner_table)):
- for j in range(len(inner_table[i])):
- inner_table[i][j] = [origin_inner_table[i][j][0], int(inner_table[i][j][1])]
- if show:
- print("table_head after repair")
- for r in inner_table:
- print('row', r)
- print("="*80)
- # 按表头分割表格
- head_list = sliceTable(inner_table)
- return inner_table, head_list
- def setHead_incontext(inner_table,pat_head,fix_value="~~",prob_min=0.5):
- data_x,data_position = getPredictor("form").getModel("context").encode(inner_table)
- predict_y = getPredictor("form").getModel("context").predict(data_x)
- for _position,_y in zip(data_position,predict_y):
- _w = _position[0]
- _h = _position[1]
- if _y[1]>prob_min:
- inner_table[_h][_w][1] = 1
- else:
- inner_table[_h][_w][1] = 0
- _item = inner_table[_h][_w][0]
- if re.search(pat_head,_item) is not None and len(_item)<8:
- inner_table[_h][_w][1] = 1
- # print("=====")
- # for item in inner_table:
- # print(item)
- # print("======")
- height = len(inner_table)
- width = len(inner_table[0])
- for i in range(height):
- for j in range(width):
- if re.search("[::]$", inner_table[i][j][0]) and len(inner_table[i][j][0])<8:
- inner_table[i][j][1] = 1
- repairTable(inner_table)
- head_list = sliceTable(inner_table)
- # print("inner_table:",inner_table)
- return inner_table,head_list
-
- #设置表头
- def setHead_inline(inner_table,prob_min=0.64):
- pad_row = "@@"
- pad_col = "##"
- removePadding(inner_table, pad_row, pad_col)
- pad_pattern = re.compile(pad_row+"|"+pad_col)
- height = len(inner_table)
- width = len(inner_table[0])
- head_list = []
- head_list.append(0)
- #行表头
- is_head_last = False
- for i in range(height):
-
- is_head = False
- is_long_value = False
-
- #判断是否是全padding值
- is_same_value = True
- same_value = inner_table[i][0][0]
- for j in range(width):
- if inner_table[i][j][0]!=same_value and inner_table[i][j][0]!=pad_row:
- is_same_value = False
- break
-
- #predict is head or not with model
- temp_item = ""
- for j in range(width):
- temp_item += inner_table[i][j][0]+"|"
- temp_item = re.sub(pad_pattern,"",temp_item)
- form_prob = getPredictor("form").predict(formEncoding(temp_item,expand=True),type="line")
- if form_prob is not None:
- if form_prob[0][1]>prob_min:
- is_head = True
- else:
- is_head = False
-
- #print(temp_item,form_prob)
- if len(inner_table[i][0][0])>40:
- is_long_value = True
- if is_head or is_long_value or is_same_value:
- #不把连续表头分开
- if not is_head_last:
- head_list.append(i)
- if is_long_value or is_same_value:
- head_list.append(i+1)
- if is_head:
- for j in range(width):
- inner_table[i][j][1] = 1
- is_head_last = is_head
- head_list.append(height)
- #列表头
- for i in range(len(head_list)-1):
- head_begin = head_list[i]
- head_end = head_list[i+1]
- #最后一列不设置为列表头
- for i in range(width-1):
- is_head = False
-
- #predict is head or not with model
- temp_item = ""
- for j in range(head_begin,head_end):
- temp_item += inner_table[j][i][0]+"|"
- temp_item = re.sub(pad_pattern,"",temp_item)
- form_prob = getPredictor("form").predict(formEncoding(temp_item,expand=True),type="line")
- if form_prob is not None:
- if form_prob[0][1]>prob_min:
- is_head = True
- else:
- is_head = False
-
- if is_head:
- for j in range(head_begin,head_end):
- inner_table[j][i][1] = 2
- addPadding(inner_table, pad_row, pad_col)
- return inner_table,head_list
-
- #设置表头
- def setHead_withRule(inner_table,pattern,pat_value,count):
- height = len(inner_table)
- width = len(inner_table[0])
- head_list = []
- head_list.append(0)
- #行表头
- is_head_last = False
- for i in range(height):
- set_match = set()
- is_head = False
- is_long_value = False
- is_same_value = True
- same_value = inner_table[i][0][0]
- for j in range(width):
- if inner_table[i][j][0]!=same_value:
- is_same_value = False
- break
- for j in range(width):
- if re.search(pat_value,inner_table[i][j][0]) is not None:
- is_head = False
- break
- str_find = re.findall(pattern,inner_table[i][j][0])
- if len(str_find)>0:
- set_match.add(inner_table[i][j][0])
- if len(set_match)>=count:
- is_head = True
- if len(inner_table[i][0][0])>40:
- is_long_value = True
- if is_head or is_long_value or is_same_value:
- if not is_head_last:
- head_list.append(i)
- if is_head:
- for j in range(width):
- inner_table[i][j][1] = 1
- is_head_last = is_head
- head_list.append(height)
- #列表头
- for i in range(len(head_list)-1):
- head_begin = head_list[i]
- head_end = head_list[i+1]
- #最后一列不设置为列表头
- for i in range(width-1):
- set_match = set()
- is_head = False
- for j in range(head_begin,head_end):
- if re.search(pat_value,inner_table[j][i][0]) is not None:
- is_head = False
- break
- str_find = re.findall(pattern,inner_table[j][i][0])
- if len(str_find)>0:
- set_match.add(inner_table[j][i][0])
- if len(set_match)>=count:
- is_head = True
- if is_head:
- for j in range(head_begin,head_end):
- inner_table[j][i][1] = 2
- return inner_table,head_list
-
- #取得表格的处理方向
- def getDirect(inner_table,begin,end):
- '''
- column_head = set()
- row_head = set()
- widths = len(inner_table[0])
- for height in range(begin,end):
- for width in range(widths):
- if inner_table[height][width][1] ==1:
- row_head.add(height)
- if inner_table[height][width][1] ==2:
- column_head.add(width)
- company_pattern = re.compile("公司")
- if 0 in column_head and begin not in row_head:
- return "column"
- if 0 in column_head and begin in row_head:
- for height in range(begin,end):
- count = 0
- count_flag = True
- for width_index in range(width):
- if inner_table[height][width_index][1]==0:
- if re.search(company_pattern,inner_table[height][width_index][0]) is not None:
- count += 1
- else:
- count_flag = False
- if count_flag and count>=2:
- return "column"
- return "row"
- '''
- count_row_keys = 0
- count_column_keys = 0
- width = len(inner_table[0])
- if begin<end:
- for w in range(len(inner_table[begin])):
- if inner_table[begin][w][1]!=0:
- count_row_keys += 1
- for h in range(begin,end):
- if inner_table[h][0][1]!=0:
- count_column_keys += 1
-
- company_pattern = re.compile("有限(责任)?公司")
- for height in range(begin,end):
- count_set = set()
- count_flag = True
- for width_index in range(width):
- if inner_table[height][width_index][1]==0:
- if re.search(company_pattern,inner_table[height][width_index][0]) is not None:
- count_set.add(inner_table[height][width_index][0])
- else:
- count_flag = False
- if count_flag and len(count_set)>=2:
- return "column"
- # if count_column_keys>count_row_keys: #2022/2/15 此项不够严谨,造成很多错误,故取消
- # return "column"
- return "row"
-
-
- #根据表格处理方向生成句子,
- def getTableText(inner_table,head_list,key_direct=False):
- # packPattern = "(标包|[标包][号段名])"
- packPattern = "(标包|标的|标项|品目|[标包][号段名]|((项目|物资|设备|场次|标段|标的|产品)(名称)))" # 2020/11/23 大网站规则,补充采购类包名
- rankPattern = "(排名|排序|名次|序号|评标结果|评审结果|是否中标|推荐意见|评标情况|推荐顺序|选取(情况|说明))" # 2020/11/23 大网站规则,添加序号为排序
- entityPattern = "((候选|[中投]标|报价)(单位|公司|人|供应商))|供应商名称"
- moneyPattern = "([中投]标|报价)(金额|价)"
- height = len(inner_table)
- width = len(inner_table[0])
- text = ""
-
- for head_i in range(len(head_list)-1):
-
- head_begin = head_list[head_i]
- head_end = head_list[head_i+1]
-
- direct = getDirect(inner_table, head_begin, head_end)
- #若只有一行,则直接按行读取
- if head_end-head_begin==1:
- text_line = ""
- for i in range(head_begin,head_end):
- for w in range(len(inner_table[i])):
- if inner_table[i][w][1]==1:
- _punctuation = ":"
- else:
- _punctuation = "," #2021/12/15 统一为中文标点,避免 206893924 国际F座1108,1,009,197.49元
- if w>0:
- if inner_table[i][w][0]!= inner_table[i][w-1][0]:
- text_line += inner_table[i][w][0]+_punctuation
- else:
- text_line += inner_table[i][w][0]+_punctuation
- text_line = text_line+"。" if text_line!="" else text_line
- text += text_line
- else:
- #构建一个共现矩阵
- table_occurence = []
- for i in range(head_begin,head_end):
- line_oc = []
- for j in range(width):
- cell = inner_table[i][j]
- line_oc.append({"text":cell[0],"type":cell[1],"occu_count":0,"left_head":"","top_head":"","left_dis":0,"top_dis":0})
- table_occurence.append(line_oc)
- occu_height = len(table_occurence)
- occu_width = len(table_occurence[0]) if len(table_occurence)>0 else 0
- #为每个属性值寻找表头
- for i in range(occu_height):
- for j in range(occu_width):
- cell = table_occurence[i][j]
- #是属性值
- if cell["type"]==0 and cell["text"]!="":
- left_head = ""
- top_head = ""
- find_flag = False
- temp_head = ""
- for loop_i in range(1,i+1):
- if not key_direct:
- key_values = [1,2]
- else:
- key_values = [1]
- if table_occurence[i-loop_i][j]["type"] in key_values:
- if find_flag:
- if table_occurence[i-loop_i][j]["text"]!=temp_head:
- top_head = table_occurence[i-loop_i][j]["text"]+":"+top_head
- else:
- top_head = table_occurence[i-loop_i][j]["text"]+":"+top_head
- find_flag = True
- temp_head = table_occurence[i-loop_i][j]["text"]
- table_occurence[i-loop_i][j]["occu_count"] += 1
- else:
- #找到表头后遇到属性值就返回
- if find_flag:
- break
- cell["top_head"] += top_head
- find_flag = False
- temp_head = ""
- for loop_j in range(1,j+1):
- if not key_direct:
- key_values = [1,2]
- else:
- key_values = [2]
- if table_occurence[i][j-loop_j]["type"] in key_values:
- if find_flag:
- if table_occurence[i][j-loop_j]["text"]!=temp_head:
- left_head = table_occurence[i][j-loop_j]["text"]+":"+left_head
- else:
- left_head = table_occurence[i][j-loop_j]["text"]+":"+left_head
- find_flag = True
- temp_head = table_occurence[i][j-loop_j]["text"]
- table_occurence[i][j-loop_j]["occu_count"] += 1
- else:
- if find_flag:
- break
- cell["left_head"] += left_head
- if direct=="row":
- for i in range(occu_height):
- pack_text = ""
- rank_text = ""
- entity_text = ""
- text_line = ""
- money_text = ""
- #在同一句话中重复的可以去掉
- text_set = set()
- head = ""
- last_text = ""
- for j in range(width):
- cell = table_occurence[i][j]
- if cell["type"]==0 or (cell["type"]==1 and cell["occu_count"]==0):
- cell = table_occurence[i][j]
- head = (cell["top_head"]+":") if len(cell["top_head"])>0 else ""
- if re.search("[单报标限总]价|金额|成交报?价|报价|供应商|候选人|中标人|[利费]率|负责人|工期|服务(期限?|年限|时间|日期|周期)|(履约|履行)期限|合同(期限?|(完成|截止)(日期|时间))", head):
- head = cell["left_head"] + head
- else:
- head += cell["left_head"]
- if str(head+cell["text"]) in text_set:
- continue
- if re.search(packPattern,head) is not None:
- pack_text += head+cell["text"]+","
- elif re.search(rankPattern,head) is not None and re.search('(排名|排序|名次|顺序):?第?[\d一二三]', rank_text)==None: # 2020/11/23 大网站规则发现问题,if 改elif 20240620修复同时有排名及评标情况造成错误
- #排名替换为同一种表达
- rank_text += head+cell["text"]+","
- #print(rank_text)
- elif re.search(entityPattern,head) is not None:
- entity_text += head+cell["text"]+","
- #print(entity_text)
- else:
- if re.search(moneyPattern,head) is not None and entity_text!="":
- money_text += head+cell["text"]+","
- else:
- text_line += head+cell["text"]+","
- text_set.add(str(head+cell["text"]))
- last_text = cell['text']
- tr_text = pack_text+rank_text+entity_text+money_text+text_line
- text += pack_text+rank_text+entity_text+money_text+text_line
- # text = text[:-1] + "。" if len(text) > 0 else text
- if len(text_set-set([' ']))==1 and head == '' and len(last_text)< 25: # 修复367694716分两行表达
- text = text if re.search('\w$', text[:-1]) else text[:-1]
- elif (width == 2 or len(text_set)==1) and head != '' and len(tr_text)<50: # 修复494731937只有两行的,分句不合理
- text = text if re.search('\w$', text[:-1]) else text[:-1]
- else:
- text = text[:-1] + "。"
- else:
- for j in range(occu_width):
- pack_text = ""
- rank_text = ""
- entity_text = ""
- text_line = ""
- text_set = set()
- for i in range(occu_height):
- cell = table_occurence[i][j]
- if cell["type"]==0 or (cell["type"]==1 and cell["occu_count"]==0):
- cell = table_occurence[i][j]
- head = (cell["left_head"]+"") if len(cell["left_head"])>0 else ""
- if re.search("[单报标限总]价|金额|成交报?价|报价|供应商|候选人|中标人|[利费]率|负责人|工期|服务(期限?|年限|时间|日期|周期)|(履约|履行)期限|合同(期限?|(完成|截止)(日期|时间))", head):
- head = cell["top_head"] + head
- else:
- head += cell["top_head"]
- if str(head+cell["text"]) in text_set:
- continue
- if re.search(packPattern,head) is not None:
- pack_text += head+cell["text"]+","
- elif re.search(rankPattern,head) is not None: # 2020/11/23 大网站规则发现问题,if 改elif
- #排名替换为同一种表达
- rank_text += head+cell["text"]+","
- #print(rank_text)
- elif re.search(entityPattern,head) is not None and \
- re.search('业绩|资格|条件',head)==None and re.search('业绩',cell["text"])==None : #2021/10/19 解决包含业绩的行调到前面问题
- entity_text += head+cell["text"]+","
- #print(entity_text)
- else:
- text_line += head+cell["text"]+","
- text_set.add(str(head+cell["text"]))
- text += pack_text+rank_text+entity_text+text_line
- text = text[:-1]+"。" if len(text)>0 else text
- # if direct=="row":
- # for i in range(head_begin,head_end):
- # pack_text = ""
- # rank_text = ""
- # entity_text = ""
- # text_line = ""
- # #在同一句话中重复的可以去掉
- # text_set = set()
- # for j in range(width):
- # cell = inner_table[i][j]
- # #是属性值
- # if cell[1]==0 and cell[0]!="":
- # head = ""
- #
- # find_flag = False
- # temp_head = ""
- # for loop_i in range(0,i+1-head_begin):
- # if not key_direct:
- # key_values = [1,2]
- # else:
- # key_values = [1]
- # if inner_table[i-loop_i][j][1] in key_values:
- # if find_flag:
- # if inner_table[i-loop_i][j][0]!=temp_head:
- # head = inner_table[i-loop_i][j][0]+":"+head
- # else:
- # head = inner_table[i-loop_i][j][0]+":"+head
- # find_flag = True
- # temp_head = inner_table[i-loop_i][j][0]
- # else:
- # #找到表头后遇到属性值就返回
- # if find_flag:
- # break
- #
- # find_flag = False
- # temp_head = ""
- #
- #
- #
- # for loop_j in range(1,j+1):
- # if not key_direct:
- # key_values = [1,2]
- # else:
- # key_values = [2]
- # if inner_table[i][j-loop_j][1] in key_values:
- # if find_flag:
- # if inner_table[i][j-loop_j][0]!=temp_head:
- # head = inner_table[i][j-loop_j][0]+":"+head
- # else:
- # head = inner_table[i][j-loop_j][0]+":"+head
- # find_flag = True
- # temp_head = inner_table[i][j-loop_j][0]
- # else:
- # if find_flag:
- # break
- #
- # if str(head+inner_table[i][j][0]) in text_set:
- # continue
- # if re.search(packPattern,head) is not None:
- # pack_text += head+inner_table[i][j][0]+","
- # elif re.search(rankPattern,head) is not None: # 2020/11/23 大网站规则发现问题,if 改elif
- # #排名替换为同一种表达
- # rank_text += head+inner_table[i][j][0]+","
- # #print(rank_text)
- # elif re.search(entityPattern,head) is not None:
- # entity_text += head+inner_table[i][j][0]+","
- # #print(entity_text)
- # else:
- # text_line += head+inner_table[i][j][0]+","
- # text_set.add(str(head+inner_table[i][j][0]))
- # text += pack_text+rank_text+entity_text+text_line
- # text = text[:-1]+"。" if len(text)>0 else text
- # else:
- # for j in range(width):
- #
- # rank_text = ""
- # entity_text = ""
- # text_line = ""
- # text_set = set()
- # for i in range(head_begin,head_end):
- # cell = inner_table[i][j]
- # #是属性值
- # if cell[1]==0 and cell[0]!="":
- # find_flag = False
- # head = ""
- # temp_head = ""
- #
- # for loop_j in range(1,j+1):
- # if not key_direct:
- # key_values = [1,2]
- # else:
- # key_values = [2]
- # if inner_table[i][j-loop_j][1] in key_values:
- # if find_flag:
- # if inner_table[i][j-loop_j][0]!=temp_head:
- # head = inner_table[i][j-loop_j][0]+":"+head
- # else:
- # head = inner_table[i][j-loop_j][0]+":"+head
- # find_flag = True
- # temp_head = inner_table[i][j-loop_j][0]
- # else:
- # if find_flag:
- # break
- # find_flag = False
- # temp_head = ""
- # for loop_i in range(0,i+1-head_begin):
- # if not key_direct:
- # key_values = [1,2]
- # else:
- # key_values = [1]
- # if inner_table[i-loop_i][j][1] in key_values:
- # if find_flag:
- # if inner_table[i-loop_i][j][0]!=temp_head:
- # head = inner_table[i-loop_i][j][0]+":"+head
- # else:
- # head = inner_table[i-loop_i][j][0]+":"+head
- # find_flag = True
- # temp_head = inner_table[i-loop_i][j][0]
- # else:
- # if find_flag:
- # break
- # if str(head+inner_table[i][j][0]) in text_set:
- # continue
- # if re.search(rankPattern,head) is not None:
- # rank_text += head+inner_table[i][j][0]+","
- # #print(rank_text)
- # elif re.search(entityPattern,head) is not None:
- # entity_text += head+inner_table[i][j][0]+","
- # #print(entity_text)
- # else:
- # text_line += head+inner_table[i][j][0]+","
- # text_set.add(str(head+inner_table[i][j][0]))
- # text += rank_text+entity_text+text_line
- # text = text[:-1]+"。" if len(text)>0 else text
- return text
- def get_table_text_kv(inner_table, head_list, key_direct=False):
- packPattern = "(标包|标的|标项|品目|[标包][号段名]|((项目|物资|设备|场次|标段|标的|产品)(名称)))" # 2020/11/23 大网站规则,补充采购类包名
- rankPattern = "(排名|排序|名次|序号|评标结果|评审结果|是否中标|推荐意见|评标情况|推荐顺序|选取(情况|说明))" # 2020/11/23 大网站规则,添加序号为排序
- entityPattern = "((候选|[中投]标|报价)(单位|公司|人|供应商))|供应商名称"
- moneyPattern = "([中投]标|报价)(金额|价)"
- width = len(inner_table[0])
- text = ""
- all_table_occurence = []
- for head_i in range(len(head_list) - 1):
- head_begin = head_list[head_i]
- head_end = head_list[head_i + 1]
- direct = getDirect(inner_table, head_begin, head_end)
- # print(inner_table[head_begin:head_end])
- # print('direct', direct)
- # 构建一个共现矩阵
- table_occurence = []
- for i in range(head_begin, head_end):
- line_oc = []
- for j in range(width):
- cell = inner_table[i][j]
- line_oc.append(
- {"text": cell[0], "type": cell[1], "occu_count": 0, "left_head": "", "top_head": "",
- "left_dis": 0, "top_dis": 0,
- "text_row_index": i, "text_col_index": j
- })
- table_occurence.append(line_oc)
- occu_height = len(table_occurence)
- occu_width = len(table_occurence[0]) if len(table_occurence) > 0 else 0
- # 为每个属性值寻找表头
- for i in range(occu_height):
- for j in range(occu_width):
- cell = table_occurence[i][j]
- # 是属性值
- if cell["type"] == 0 and cell["text"] != "":
- left_head = ""
- top_head = ""
- find_flag = False
- temp_head = ""
- head_row_col_list = []
- for loop_i in range(1, i + 1):
- if not key_direct:
- key_values = [1, 2]
- else:
- key_values = [1]
- if table_occurence[i - loop_i][j]["type"] in key_values:
- if find_flag:
- if table_occurence[i - loop_i][j]["text"] != temp_head:
- if cell.get("top_head_list"):
- cell["top_head_list"] += [table_occurence[i - loop_i][j]["text"] + ":"]
- else:
- cell["top_head_list"] = [table_occurence[i - loop_i][j]["text"] + ":"]
- top_head = table_occurence[i - loop_i][j]["text"] + ":" + top_head
- head_row_col_list.append([i - loop_i, j])
- else:
- if cell.get("top_head_list"):
- cell["top_head_list"] += [table_occurence[i - loop_i][j]["text"] + ":"]
- else:
- cell["top_head_list"] = [table_occurence[i - loop_i][j]["text"] + ":"]
- top_head = table_occurence[i - loop_i][j]["text"] + ":" + top_head
- head_row_col_list.append([i - loop_i, j])
- find_flag = True
- temp_head = table_occurence[i - loop_i][j]["text"]
- table_occurence[i - loop_i][j]["occu_count"] += 1
- else:
- # 找到表头后遇到属性值就返回
- if find_flag:
- break
- cell["top_head"] += top_head
- if cell.get("top_head_row_index"):
- cell["top_head_row_index"] += [x[0] for x in head_row_col_list]
- else:
- cell["top_head_row_index"] = [x[0] for x in head_row_col_list]
- if cell.get("top_head_col_index"):
- cell["top_head_col_index"] += [x[1] for x in head_row_col_list]
- else:
- cell["top_head_col_index"] = [x[1] for x in head_row_col_list]
- find_flag = False
- temp_head = ""
- head_row_col_list = []
- for loop_j in range(1, j + 1):
- if not key_direct:
- key_values = [1, 2]
- else:
- key_values = [2]
- if table_occurence[i][j - loop_j]["type"] in key_values:
- if find_flag:
- if table_occurence[i][j - loop_j]["text"] != temp_head:
- if cell.get("left_head_list"):
- cell["left_head_list"] += [table_occurence[i][j - loop_j]["text"] + ":"]
- else:
- cell["left_head_list"] = [table_occurence[i][j - loop_j]["text"] + ":"]
- left_head = table_occurence[i][j - loop_j]["text"] + ":" + left_head
- head_row_col_list.append([i, j - loop_j])
- else:
- if cell.get("left_head_list"):
- cell["left_head_list"] += [table_occurence[i][j - loop_j]["text"] + ":"]
- else:
- cell["left_head_list"] = [table_occurence[i][j - loop_j]["text"] + ":"]
- left_head = table_occurence[i][j - loop_j]["text"] + ":" + left_head
- head_row_col_list.append([i, j - loop_j])
- find_flag = True
- temp_head = table_occurence[i][j - loop_j]["text"]
- table_occurence[i][j - loop_j]["occu_count"] += 1
- else:
- if find_flag:
- break
- cell["left_head"] += left_head
- if cell.get("left_head_row_index"):
- cell["left_head_row_index"] += [x[0] for x in head_row_col_list]
- else:
- cell["left_head_row_index"] = [x[0] for x in head_row_col_list]
- if cell.get("left_head_col_index"):
- cell["left_head_col_index"] += [x[1] for x in head_row_col_list]
- else:
- cell["left_head_col_index"] = [x[1] for x in head_row_col_list]
- # 连接表头和属性值
- if direct == "row":
- for i in range(occu_height):
- pack_text = ""
- rank_text = ""
- entity_text = ""
- text_line = ""
- money_text = ""
- # 在同一句话中重复的可以去掉
- text_set = set()
- head = ""
- last_text = ""
- pack_text_location = []
- rank_text_location = []
- entity_text_location = []
- text_line_location = []
- money_text_location = []
- for j in range(width):
- cell = table_occurence[i][j]
- if cell["type"] == 0 or (cell["type"] == 1 and cell["occu_count"] == 0):
- cell = table_occurence[i][j]
- head = (cell["top_head"] + ":") if len(cell["top_head"]) > 0 else ""
- now_top_head = copy.deepcopy(head)
- now_left_head = copy.deepcopy(cell["left_head"])
- if re.search(
- "[单报标限总]价|金额|成交报?价|报价|供应商|候选人|中标人|[利费]率|负责人|工期|服务(期限?|年限|时间|日期|周期)|("
- "履约|履行)期限|合同(期限?|(完成|截止)(日期|时间))",
- head):
- head = cell["left_head"] + head
- left_first = 1
- else:
- head += cell["left_head"]
- left_first = 0
- # print('len(text), len(sub_text), len(head)', cell["text"], len(text), len(sub_text), len(head))
- # print('text111', text)
- # print('pack_text, rank_text, entity_text, money_text, text_line', '1'+pack_text, '2'+rank_text, '3'+entity_text, '4'+money_text, '5'+text_line)
- # print('head', head)
- # print('sub_text111', sub_text)
- if str(head + cell["text"]) in text_set:
- cell['drop'] = 1
- continue
- if re.search(packPattern, head) is not None:
- pack_text += head + cell["text"] + ","
- pack_text_location += [[i, j, head + cell["text"] + ",", now_left_head, now_top_head, left_first]]
- # 2020/11/23 大网站规则发现问题,if 改elif 20240620修复同时有排名及评标情况造成错误
- elif re.search(rankPattern, head) is not None and re.search('(排名|排序|名次|顺序):?第?[\d一二三]', rank_text) is None:
- # 排名替换为同一种表达
- rank_text += head + cell["text"] + ","
- rank_text_location += [[i, j, head + cell["text"] + ",", now_left_head, now_top_head, left_first]]
- elif re.search(entityPattern, head) is not None:
- entity_text += head + cell["text"] + ","
- entity_text_location += [[i, j, head + cell["text"] + ",", now_left_head, now_top_head, left_first]]
- else:
- if re.search(moneyPattern, head) is not None and entity_text != "":
- money_text += head + cell["text"] + ","
- money_text_location += [[i, j, head + cell["text"] + ",", now_left_head, now_top_head, left_first]]
- else:
- text_line += head + cell["text"] + ","
- text_line_location += [[i, j, head + cell["text"] + ",", now_left_head, now_top_head, left_first]]
- text_set.add(str(head + cell["text"]))
- last_text = cell['text']
- # 计算key value在sentence的index
- head_location_list = pack_text_location + rank_text_location + entity_text_location + text_line_location + money_text_location
- current_loc = 0
- for ii, jj, head_text, now_left_head, now_top_head, left_first in head_location_list:
- cell = table_occurence[ii][jj]
- # 左表头先于右表头
- if left_first:
- cell['left_head_sen_index'] = len(text) + current_loc
- cell['top_head_sen_index'] = len(text) + current_loc + len(now_left_head)
- else:
- cell['left_head_sen_index'] = len(text) + current_loc + len(now_top_head)
- cell['top_head_sen_index'] = len(text) + current_loc
- cell['text_sen_index'] = len(text) + current_loc + len(now_left_head + now_top_head)
- current_loc += len(head_text)
- tr_text = pack_text + rank_text + entity_text + money_text + text_line
- text += pack_text + rank_text + entity_text + money_text + text_line
- # 修复367694716分两行表达
- if len(text_set - set([' '])) == 1 and head == '' and len(last_text) < 25:
- text = text if re.search('\w$', text[:-1]) else text[:-1]
- # 修复494731937只有两行的,分句不合理
- elif (width == 2 or len(text_set) == 1) and head != '' and len(tr_text) < 50:
- text = text if re.search('\w$', text[:-1]) else text[:-1]
- else:
- text = text[:-1] + "。"
- else:
- for j in range(occu_width):
- pack_text = ""
- rank_text = ""
- entity_text = ""
- text_line = ""
- text_set = set()
- pack_text_location = []
- rank_text_location = []
- entity_text_location = []
- text_line_location = []
- money_text_location = []
- for i in range(occu_height):
- cell = table_occurence[i][j]
- if cell["type"] == 0 or (cell["type"] == 1 and cell["occu_count"] == 0):
- cell = table_occurence[i][j]
- head = (cell["left_head"] + "") if len(cell["left_head"]) > 0 else ""
- now_top_head = copy.deepcopy(cell["top_head"])
- now_left_head = copy.deepcopy(head)
- if re.search("[单报标限总]价|金额|成交报?价|报价|供应商|候选人|中标人|[利费]率|负责人|工期|服务(期限?|年限|时间|日期|周期)|(履约|履行)期限|合同(期限?|(完成|截止)(日期|时间))", head):
- head = cell["top_head"] + head
- left_first = 0
- else:
- head += cell["top_head"]
- left_first = 1
- if str(head + cell["text"]) in text_set:
- cell['drop'] = 1
- continue
- if re.search(packPattern, head) is not None:
- pack_text += head + cell["text"] + ","
- pack_text_location += [[i, j, head + cell["text"] + ",", now_left_head, now_top_head, left_first]]
- # 2020/11/23 大网站规则发现问题,if 改elif
- elif re.search(rankPattern, head) is not None:
- # 排名替换为同一种表达
- rank_text += head + cell["text"] + ","
- rank_text_location += [[i, j, head + cell["text"] + ",", now_left_head, now_top_head, left_first]]
- # 2021/10/19 解决包含业绩的行调到前面问题
- elif re.search(entityPattern, head) is not None and \
- re.search('业绩|资格|条件', head) is None and re.search('业绩', cell["text"]) is None:
- entity_text += head + cell["text"] + ","
- entity_text_location += [[i, j, head + cell["text"] + ",", now_left_head, now_top_head, left_first]]
- else:
- text_line += head + cell["text"] + ","
- text_line_location += [[i, j, head + cell["text"] + ",", now_left_head, now_top_head, left_first]]
- text_set.add(str(head + cell["text"]))
- # 计算key value在sentence的index
- head_location_list = pack_text_location + rank_text_location + entity_text_location + text_line_location + money_text_location
- current_loc = 0
- for ii, jj, head_text, now_left_head, now_top_head, left_first in head_location_list:
- cell = table_occurence[ii][jj]
- # 左表头先于右表头
- if left_first:
- cell['left_head_sen_index'] = len(text) + current_loc
- cell['top_head_sen_index'] = len(text) + current_loc + len(now_left_head)
- else:
- cell['left_head_sen_index'] = len(text) + current_loc + len(now_top_head)
- cell['top_head_sen_index'] = len(text) + current_loc
- cell['text_sen_index'] = len(text) + current_loc + len(now_left_head + now_top_head)
- current_loc += len(head_text)
- text += pack_text + rank_text + entity_text + text_line
- text = text[:-1] + "。" if len(text) > 0 else text
- all_table_occurence += table_occurence
- return text, all_table_occurence
- def process_dict(text, table):
- kv_list = []
- kv_dict_list = []
- # print('text', len(text), text, ),
- # print('table', table)
- for r_index, row in enumerate(table):
- for c_index, col in enumerate(row):
- # print('col', col)
- if col['type'] == 1:
- continue
- if col.get('drop'):
- continue
- if not col.get('left_head_list') and not col.get('top_head_list'):
- _d = {
- 'value': col['text'],
- 'value_row_index': col['text_row_index'],
- 'value_col_index': col['text_col_index'],
- 'value_sen_index': col['text_sen_index'],
- 'sen_value': text[col['text_sen_index']:col['text_sen_index'] + len(col['text'])],
- }
- kv_dict_list.append(_d)
- continue
- if col.get('text_sen_index') and col.get('text_sen_index') >= len(text):
- # print('continue1')
- continue
- if col.get('left_head_list'):
- # head, head_row_index, head_col_index 按文本顺序排序
- zip_list = list(
- zip(col.get('left_head_list'), col.get('left_head_row_index'), col.get('left_head_col_index')))
- zip_list.sort(key=lambda x: (x[1], x[2]))
- col['left_head_list'], col['left_head_row_index'], col['left_head_col_index'] = zip(*zip_list)
- last_head = ""
- for h_index, head in enumerate(col.get('left_head_list')):
- _d = {
- 'key': head,
- 'value': col['text'],
- 'key_row_index': col['left_head_row_index'][h_index],
- 'key_col_index': col['left_head_col_index'][h_index],
- 'key_sen_index': col['left_head_sen_index'] + len(last_head),
- 'value_row_index': col['text_row_index'],
- 'value_col_index': col['text_col_index'],
- 'value_sen_index': col['text_sen_index'],
- 'sen_key': text[
- col['left_head_sen_index'] + len(last_head):col['left_head_sen_index'] + len(
- last_head) + len(head)],
- 'sen_value': text[col['text_sen_index']:col['text_sen_index'] + len(col['text'])],
- }
- kv_dict_list.append(_d)
- last_head += head
- if col.get('top_head_list'):
- # head, head_row_index, head_col_index 按文本顺序排序
- zip_list = list(
- zip(col.get('top_head_list'), col.get('top_head_row_index'), col.get('top_head_col_index')))
- zip_list.sort(key=lambda x: (x[1], x[2]))
- col['top_head_list'], col['top_head_row_index'], col['top_head_col_index'] = zip(*zip_list)
- last_head = ""
- for h_index, head in enumerate(col.get('top_head_list')):
- _d = {
- 'key': head,
- 'value': col['text'],
- 'key_row_index': col['top_head_row_index'][h_index],
- 'key_col_index': col['top_head_col_index'][h_index],
- 'key_sen_index': col['top_head_sen_index'] + len(last_head),
- 'value_row_index': col['text_row_index'],
- 'value_col_index': col['text_col_index'],
- 'value_sen_index': col['text_sen_index'],
- 'sen_key': text[col['top_head_sen_index'] + len(last_head):col['top_head_sen_index'] + len(
- last_head) + len(head)],
- 'sen_value': text[col['text_sen_index']:col['text_sen_index'] + len(col['text'])],
- }
- kv_dict_list.append(_d)
- last_head += head
- return kv_list, kv_dict_list
- def removeFix(inner_table,fix_value="~~"):
- height = len(inner_table)
- width = len(inner_table[0])
- for h in range(height):
- for w in range(width):
- if inner_table[h][w][0]==fix_value:
- inner_table[h][w][0] = ""
-
- def trunTable(tbody,in_attachment):
- # print(tbody.find('tbody'))
- # 附件中的表格,排除异常错乱的表格
- if in_attachment:
- if tbody.name=='table':
- _tbody = tbody.find('tbody')
- if _tbody is None:
- _tbody = tbody
- else:
- _tbody = tbody
- _td_len_list = []
- for _tr in _tbody.find_all(recursive=False):
- len_td = len(_tr.find_all(recursive=False))
- _td_len_list.append(len_td)
- if _td_len_list:
- if len(list(set(_td_len_list))) >= 8 or max(_td_len_list) > 100:
- string_list = [re.sub("\s+","",i)for i in tbody.strings if i and i!='\n']
- tbody.string = ",".join(string_list)
- table_max_len = 30000
- tbody.string = tbody.string[:table_max_len]
- tbody.name = "turntable"
- if return_kv:
- return None, None, None
- return None
- # fixSpan(tbody)
- # inner_table = getTable(tbody)
- # inner_table = fixTable(inner_table)
- table2list = TableTag2List()
- return_html_table = True if return_kv else False
- if return_html_table:
- inner_table, html_table = table2list.table2list(tbody, segment, return_html_table,return_kv=return_kv)
- inner_table = fixTable(inner_table)
- html_table = fixTable(html_table, "")
- else:
- inner_table = table2list.table2list(tbody, segment,return_kv=return_kv)
- inner_table = fixTable(inner_table)
- if inner_table == []:
- string_list = [re.sub("\s+", "", i) for i in tbody.strings if i and i != '\n']
- tbody.string = ",".join(string_list)
- table_max_len = 30000
- tbody.string = tbody.string[:table_max_len]
- # log('异常表格直接取全文')
- tbody.name = "turntable"
- if return_kv:
- return None, None, None
- return None
- if len(inner_table)>0 and len(inner_table[0])>0:
- for tr in inner_table:
- for td in tr:
- if isinstance(td, str):
- tbody.string = segment(tbody,final=False)
- table_max_len = 30000
- tbody.string = tbody.string[:table_max_len]
- # log('异常表格,不做表格处理,直接取全文')
- tbody.name = "turntable"
- if return_kv:
- return None, None, None
- return None
- #inner_table,head_list = setHead_withRule(inner_table,pat_head,pat_value,3)
- #inner_table,head_list = setHead_inline(inner_table)
- # inner_table, head_list = setHead_initem(inner_table,pat_head)
- inner_table, head_list = set_head_model(inner_table)
- # inner_table,head_list = setHead_incontext(inner_table,pat_head)
- # print("table_head", inner_table)
- # print("head_list", head_list)
- # for begin in range(len(head_list[:-1])):
- # for item in inner_table[head_list[begin]:head_list[begin+1]]:
- # print(item)
- # print("====")
- removeFix(inner_table)
-
- # print("----")
- # print(head_list)
- # for item in inner_table:
- # print(item)
- # print('inner_table111', inner_table)
- if return_kv:
- text1, table = get_table_text_kv(inner_table, head_list)
- tbody.string = text1
- kv_list, kv_dict_list = process_dict(text1, table)
- # html放入dict
- for kv_dict in kv_dict_list:
- html = html_table[kv_dict.get('value_row_index')][kv_dict.get('value_col_index')]
- kv_dict['value_html'] = html
- else:
- tbody.string = getTableText(inner_table,head_list)
- table_max_len = 30000
- tbody.string = tbody.string[:table_max_len]
- # print(tbody.string)
- tbody.name = "turntable"
- if return_kv:
- return inner_table, kv_dict_list, text1
- else:
- return inner_table
- if return_kv:
- return None, None, None
- return None
-
- pat_head = re.compile('^(名称|序号|项目|标项|工程|品目[一二三四1234]|第[一二三四1234](标段|名|候选人|中标)|包段|标包|分包|包号|货物|单位|数量|价格|报价|金额|总价|单价|[招投中]标|候选|编号|得分|评委|评分|名次|排名|排序|科室|方式|工期|时间|产品|开始|结束|联系|日期|面积|姓名|证号|备注|级别|地[点址]|类型|代理|制造|企业资质|质量目标|工期目标|(需求|服务|项目|施工|采购|招租|出租|转让|出让|业主|询价|委托|权属|招标|竞得|抽取|承建)(人|方|单位)(名称)?|(供应商|供货商|服务商)(名称)?)$')
- #pat_head = re.compile('(名称|序号|项目|工程|品目[一二三四1234]|第[一二三四1234](标段|候选人|中标)|包段|包号|货物|单位|数量|价格|报价|金额|总价|单价|[招投中]标|供应商|候选|编号|得分|评委|评分|名次|排名|排序|科室|方式|工期|时间|产品|开始|结束|联系|日期|面积|姓名|证号|备注|级别|地[点址]|类型|代理)')
- pat_value = re.compile("(\d{2,}.\d{1}|\d+年\d+月|\d{8,}|\d{3,}-\d{6,}|有限[责任]*公司|^\d+$)")
- list_innerTable = []
- # 2022/2/9 删除干扰标签
- for tag in soup.find_all('option'): #例子: 216661412
- if 'selected' not in tag.attrs:
- tag.extract()
- for ul in soup.find_all('ul'): #例子 156439663 多个不同channel 类别的标题
- if ul.find_all('li') == ul.findChildren(recursive=False) and len(set(re.findall(
- '招标公告|中标结果公示|中标候选人公示|招标答疑|开标评标|合同履?约?公示|资格评审',
- ul.get_text(), re.S)))>3:
- ul.extract()
- # tbodies = soup.find_all('table')
- # 遍历表格中的每个tbody
- tbodies = []
- in_attachment = False
- if soup.name=="table":
- tbodies.append((soup,in_attachment))
- for _part in soup.find_all():
- if _part.name=='table':
- tbodies.append((_part,in_attachment))
- elif _part.name=='div':
- if 'class' in _part.attrs and "richTextFetch" in _part['class']:
- in_attachment = True
- if return_kv and tbodies:
- tbodies = tbodies[:1]
- #逆序处理嵌套表格
- # print('len(tbodies)1', len(tbodies))
- # for tbody_index in range(1,len(tbodies)+1):
- tbody_index = 1
- while tbody_index < len(tbodies)+1:
- tbody,_in_attachment = tbodies[len(tbodies)-tbody_index]
- if len(tbody.find_all('tr')) == 1 and tbody_index > 0 and len(
- tbodies[tbody_index - 1][0].find_all('tr')) == 1 and len(tbody.find_all(['th', 'td'])) == len(
- tbodies[tbody_index - 1][0].find_all(['th', 'td'])): # 处理相邻表格都只有一行的情况;例:526321576
- for row in tbody.find_all('tr'):
- if tbodies[tbody_index - 1][0].tbody:
- tbodies[tbody_index - 1][0].tbody.append(row)
- else:
- tbodies[tbody_index - 1][0].append(row)
- inner_table = trunTable(tbodies[tbody_index - 1][0], _in_attachment)
- if inner_table:
- list_innerTable.append(inner_table)
- tbody_index += 2
- continue
- inner_table = trunTable(tbody,_in_attachment)
- list_innerTable.append(inner_table)
- tbody_index += 1
- # tbodies = soup.find_all('tbody')
- # 遍历表格中的每个tbody
- tbodies = []
- in_attachment = False
- if soup.name=="tbody":
- tbodies.append((soup,in_attachment))
- for _part in soup.find_all():
- if _part.name == 'tbody':
- tbodies.append((_part, in_attachment))
- elif _part.name == 'div':
- if 'class' in _part.attrs and "richTextFetch" in _part['class']:
- in_attachment = True
- if return_kv and tbodies:
- tbodies = tbodies[:1]
- #逆序处理嵌套表格
- tbody_index = 1
- # for tbody_index in range(1,len(tbodies)+1):
- while tbody_index < len(tbodies) + 1:
- tbody,_in_attachment = tbodies[len(tbodies)-tbody_index]
- if len(tbody.find_all('tr')) == 1 and tbody_index > 0 and len(
- tbodies[tbody_index - 1][0].find_all('tr')) == 1 and len(tbody.find_all(['th', 'td'])) == len(
- tbodies[tbody_index - 1][0].find_all(['th', 'td'])): # 处理相邻表格都只有一行的情况;例:526321576
- for row in tbody.find_all('tr'):
- if tbodies[tbody_index - 1][0].tbody:
- tbodies[tbody_index - 1][0].tbody.append(row)
- else:
- tbodies[tbody_index - 1][0].append(row)
- inner_table = trunTable(tbodies[tbody_index - 1][0], _in_attachment)
- if inner_table:
- list_innerTable.append(inner_table)
- tbody_index += 2
- continue
- inner_table = trunTable(tbody,_in_attachment)
- list_innerTable.append(inner_table)
- tbody_index += 1
- if return_kv:
- kv_list = []
- for x in list_innerTable:
- if x[1] is not None:
- kv_list.extend(x[1])
- text = ""
- for x in list_innerTable:
- if x[2] is not None:
- text += x[2]
- return soup, kv_list, text
- return soup
- # return list_innerTable
- def table_head_repair_process(_inner_table, docid=None, show=0, show_row_index=0):
- def pre_process(inner_table):
- """
- 修复前的预处理
- """
- # 循环处理单元格,一次获取需要的
- for i in range(len(inner_table)):
- for j in range(len(inner_table[i])):
- # 删除前后逗号
- inner_table[i][j][0] = re.sub('^[,, ]+', '', inner_table[i][j][0])
- inner_table[i][j][0] = re.sub('[,, ]+$', '', inner_table[i][j][0])
- inner_table[i][j][0] = re.sub('[, ]+', '', inner_table[i][j][0])
- return inner_table
- def repair_by_colon(inner_table):
- """
- 根据冒号修复当前格子的表头值
- """
- # 修复冒号在文本中间的,不能作为表头;(冒号后面需多个字)
- # 冒号在括号中的除外
- # 冒号在最后的,判断后一个格子是否有重复的文字
- for i in range(len(inner_table)):
- for j in range(len(inner_table[i])):
- _text = inner_table[i][j][0]
- if len(_text) >= 3 and inner_table[i][j][1] == 1:
- match = re.search('[::]', _text)
- if match:
- start_index, end_index = match.span()
- if start_index == 0:
- continue
- if end_index == len(_text):
- 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):
- inner_table[i][j][1] = 0
- inner_table[i][j+1][1] = 0
- else:
- continue
- if re.search('[((]', _text[:start_index]) and re.search('[))]', _text[end_index:]):
- continue
- m1 = re.search('[\u4e00-\u9fa50-9a-zA-Z]', _text[:start_index])
- m2 = re.search('[\u4e00-\u9fa50-9a-zA-Z]', _text[end_index:])
- if m1 and m2 and (len(m2.group()) >= 2 or m2.group() in ['是', '否']):
- inner_table[i][j][1] = 0
- return inner_table
- def repair_by_duplicate(inner_table):
- """
- 根据列重复修复当前格子的表头值
- """
- # 统计每个值的表头情况
- col_head_dict = {}
- for i in range(len(inner_table)):
- for j in range(len(inner_table[i])):
- col = inner_table[i][j]
- if col[0] in col_head_dict.keys():
- col_head_dict[col[0]] += [col[1]]
- else:
- col_head_dict[col[0]] = [col[1]]
- # 多个重复列的预测值不同,以第一个为准
- for i in range(len(inner_table)):
- col = inner_table[i][0]
- key = col[0] + '\t' + str(0)
- dup_dict = {}
- for j in range(len(inner_table[i])):
- if inner_table[i][j][0] == col[0]:
- if key in dup_dict.keys():
- dup_dict[key] += [j]
- else:
- dup_dict[key] = [j]
- # if inner_table[i][j][1] != col[1]:
- # if col != inner_table[i][0]:
- # inner_table[i][j][1] = col[1]
- # else:
- # inner_table[i][0][1] = inner_table[i][j][1]
- # col = inner_table[i][0]
- else:
- col = inner_table[i][j]
- key = col[0] + '\t' + str(j)
- dup_dict[key] = [j]
- # print('dup_dict', dup_dict)
- #
- for key in dup_dict.keys():
- index_list = dup_dict.get(key)
- if len(index_list) <= 1:
- continue
- # 需要表头不同
- table_head_list = []
- for index in index_list:
- table_head_list.append(inner_table[i][index][1])
- table_head_list = list(set(table_head_list))
- if len(table_head_list) <= 1:
- continue
- # 若是职业特殊处理
- col = key.split('\t')[0]
- if re.search('([^人]员|工程师|建造师|经理|安全负责人|技术负责人|合同商务负责人)$', col):
- table_head_flag = 0
- # 看是否包含表头
- else:
- table_head_flag = 0
- for index in index_list:
- if inner_table[i][index][1] == 1:
- table_head_flag = 1
- break
- table_head = None
- if index_list[0] > 0 and index_list[-1] == len(inner_table[i]) - 1:
- table_head = inner_table[i][index_list[0]][1]
- elif index_list[0] > 0 and index_list[-1] != len(inner_table[i]) - 1:
- # 查看前面是否有表头-非表头表达
- is_head_not_head = 0
- for k in range(index_list[0]):
- if k+1 < index_list[0] and inner_table[i][k][1] == 1 and inner_table[i][k+1][1] == 0:
- is_head_not_head = 1
- break
- # 查看前后有没有表头
- start_has_head = 0
- end_has_head = 0
- if not is_head_not_head:
- for k in range(index_list[0], len(inner_table[i])):
- if inner_table[i][k][0] == inner_table[i][index_list[0]][0]:
- continue
- if inner_table[i][k][1] == 1:
- end_has_head = 1
- break
- for k in range(index_list[0]):
- if inner_table[i][k][0] == inner_table[i][index_list[0]][0]:
- continue
- if inner_table[i][k][1] == 1:
- start_has_head = 1
- break
- head_list = col_head_dict.get(inner_table[i][index_list[0]][0])
- if is_head_not_head:
- table_head = table_head_flag
- elif len(head_list) >= 4:
- if head_list.count(0) > head_list.count(1):
- table_head = 0
- else:
- table_head = 1
- elif not start_has_head and not end_has_head:
- table_head = 0
- else:
- table_head = table_head_flag
- elif index_list[0] == 0 and index_list[-1] == len(inner_table[i]) - 1:
- table_head = table_head_flag
- elif index_list[0] == 0 and index_list[-1] != len(inner_table[i]) - 1:
- head_list = col_head_dict.get(inner_table[i][index_list[0]][0])
- if len(head_list) >= 4:
- if head_list.count(0) > head_list.count(1):
- table_head = 0
- else:
- table_head = 1
- else:
- table_head = table_head_flag
- if table_head is not None:
- for index in index_list:
- inner_table[i][index][1] = table_head
- return inner_table
- def repair_by_around(inner_table):
- """
- 根据周围的表头值修复当前格子的表头值
- """
- one_head_index_list = []
- zero_head_index_list = []
- all_head_index_list = []
- one_not_head_index_list = []
- no_dup_index_cnt_dict = {}
- for i in range(len(inner_table)):
- head_cnt = 0
- head_index = None
- head_dict = {}
- for j in range(len(inner_table[i])):
- # 统计表头数
- if inner_table[i][j][1] == 1:
- head_cnt += 1
- head_index = j
- if inner_table[i][j][0] not in ['~~', '', ' ']:
- if inner_table[i][j][0] in head_dict.keys():
- head_dict[inner_table[i][j][0]] += 1
- else:
- head_dict[inner_table[i][j][0]] = 1
- no_dup_index_cnt_dict[i] = len(head_dict.keys())
- # 表头数list
- if head_cnt == 0:
- zero_head_index_list.append(i)
- elif head_cnt == 1:
- # 这个单个表头需满足前面有非表头
- find_flag = 0
- for k in range(head_index):
- if inner_table[i][k][1] == 0:
- find_flag = 1
- if find_flag and len(head_dict.keys()) > 2:
- one_head_index_list.append(i)
- elif head_cnt == len(inner_table[i]):
- all_head_index_list.append(i)
- elif head_cnt == len(inner_table[i]) - 1:
- one_not_head_index_list.append(i)
- # 第一行为表头,但有一个不为表头,下面行都非表头,表格行数小于4
- if 0 in one_not_head_index_list and 1 in zero_head_index_list and len(inner_table) <= 4:
- # 不相等的列值大于4
- diff_col1 = []
- for col in inner_table[0]:
- if col[0] not in diff_col1 and len(col[0]) >= 1:
- diff_col1.append(col[0])
- diff_col2 = []
- for col in inner_table[1]:
- if col[0] not in diff_col2 and len(col[0]) >= 1:
- diff_col2.append(col[0])
- if len(diff_col1) >= 4 and len(diff_col2) >= 4:
- for j in range(len(inner_table[0])):
- inner_table[0][j][1] = 1
- one_not_head_index_list.remove(0)
- all_head_index_list.append(0)
- # 一行很多列且都为表头,则剩下一个也为表头
- for i in range(len(inner_table)):
- if no_dup_index_cnt_dict.get(i) >= 5 and i in one_not_head_index_list:
- for j in range(len(inner_table[i])):
- inner_table[i][j][1] = 1
- # 一行很多列且都不为表头,则剩下一个也不为表头,除了第一个
- for i in range(len(inner_table)):
- if no_dup_index_cnt_dict.get(i) >= 5 and i in one_head_index_list \
- and inner_table[i][0][1] != 1 and inner_table[i][0][0] != '':
- for j in range(len(inner_table[i])):
- inner_table[i][j][1] = 0
- # 一整个大表格,第一行为表头,下面行中有个别格子被识别为表头
- # 候选人后面修复
- for index in one_head_index_list:
- if (index - 1 in zero_head_index_list and index - 2 in zero_head_index_list) \
- or (index - 1 in zero_head_index_list and index - 2 in all_head_index_list) \
- or (index - 1 in all_head_index_list):
- for j in range(len(inner_table[index])):
- inner_table[index][j][1] = 0
- zero_head_index_list.append(index)
- return inner_table
- def repair_by_tenderer(inner_table):
- """
- 根据第一第二第三候选人修复当前格子的表头值
- """
- # 修复第一第二第三中标候选人作为表头
- first_tenderer = ['第一中标候选人', '第一中标人', '第一中标(成交)人', '第一候选人']
- second_tenderer = ['第二中标候选人', '第二中标(成交)候选人', '第二候选人']
- third_tenderer = ['第三中标候选人', '第三中标(成交)候选人', '第三候选人']
- # n1 next one, n2 next two, l1 last one, l2 last two
- for i in range(len(inner_table)):
- row = inner_table[i]
- n1_row, n2_row = None, None
- if i+1 < len(inner_table):
- n1_row = inner_table[i+1]
- if i+2 < len(inner_table):
- n2_row = inner_table[i+2]
- for j in range(len(row)):
- row_col = row[j]
- n1_row_col, n2_row_col = None, None
- row_n1_col, row_n2_col = None, None
- n1_row_n1_col, n2_row_n1_col, n1_row_n2_col = None, None, None
- if n1_row:
- n1_row_col = n1_row[j]
- if n2_row:
- n2_row_col = n2_row[j]
- if j+1 < len(row):
- row_n1_col = row[j+1]
- if j+2 < len(row):
- row_n2_col = row[j+2]
- if n1_row and j+1 < len(n1_row):
- n1_row_n1_col = n1_row[j+1]
- if n2_row and j+1 < len(n2_row):
- n2_row_n1_col = n2_row[j+1]
- if n1_row and j+2 < len(n1_row):
- n1_row_n2_col = n1_row[j+2]
- # 连续作为行表头
- if row_col[0] in first_tenderer and row_n1_col and row_n1_col[1] == 0:
- if n1_row_col and n1_row_col[0] in second_tenderer and n1_row_n1_col and n1_row_n1_col[1] == 0:
- inner_table[i][j][1] = 1
- inner_table[i+1][j][1] = 1
- if n2_row_col and n2_row_col[0] in third_tenderer and n2_row_n1_col and n2_row_n1_col[1] == 0:
- inner_table[i+2][j][1] = 1
- # 连续作为列表头
- if row_col[0] in first_tenderer and n1_row_col and n1_row_col[1] == 0:
- if row_n1_col and row_n1_col[0] in second_tenderer and n1_row_n1_col and n1_row_n1_col[1] == 0:
- inner_table[i][j][1] = 1
- inner_table[i][j+1][1] = 1
- if row_n2_col and row_n2_col[0] in third_tenderer and n1_row_n2_col and n1_row_n2_col[1] == 0:
- inner_table[i][j+2][1] = 1
- return inner_table
- def repair_by_keywords(inner_table):
- """
- 根据关键词修复当前格子的表头值
- """
- # 修复表头关键词未作为表头
- # 末尾匹配匹配关键词且字数小于7,直接作为表头
- head_keyword = ['供应商', '总价', '总价(元)', '总价\(元\)', '品目一', '品目二', '品目三']
- # 末尾匹配关键词且前一列为表头且与前一列文本不同,直接不做表头
- head_keyword2 = ['管理中心', '有限公司', '项目采购', '确定。', ]
- # 开头匹配关键词,直接不做表头
- head_keyword3 = ['详见', '选定', '咨询服务', '标准物资', '电汇', '承兑', '低档', '高档',
- '更换配置', '各种数据']
- # 文本匹配关键词且前一列为表头,直接作为表头
- head_keyword4 = ['综合排名', '工期(交货期)', '检测批', '检测范围', '混凝土设计强检测批的容度等级',
- '量(个)']
- # 文本在关键词中,直接不做表头
- head_keyword5 = ['殡葬用地', '电脑包', '电池']
- # 文本匹配关键词,直接不作表头
- head_keyword6 = ['市场行情', '有限公司', '能提供']
- # 末尾匹配关键词,直接不做表头
- head_keyword7 = ['基金', '结转', '结余', '税', '结余分配', '协议供货', '房屋',
- '纳税人', '自然人', '计算所得额']
- # 文本匹配关键词且整行都是表头,直接做表头
- head_keyword8 = ['备注']
- # n1 next one, n2 next two, l1 last one, l2 last two
- for i in range(len(inner_table)):
- row = inner_table[i]
- for j in range(len(row)):
- row_col = row[j]
- row_l1_col = None
- if j-1 >= 0:
- row_l1_col = row[j-1]
- for key in head_keyword:
- match = re.search(key+'$', row_col[0])
- if match and len(inner_table[i][j][0]) <= 6:
- if show:
- print('match head_keyword')
- inner_table[i][j][1] = 1
- for key in head_keyword2:
- match = re.search(key+'$', row_col[0])
- 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:
- if show:
- print('match head_keyword2')
- inner_table[i][j][1] = 0
- for key in head_keyword3:
- match = re.search('^'+key, row_col[0])
- if match and row_col[1] == 1:
- if show:
- print('match head_keyword3')
- inner_table[i][j][1] = 0
- for key in head_keyword4:
- match = re.search(key, row_col[0])
- if j > 0 and row_l1_col and row_l1_col[1] == 1 and match and row_col[1] == 0:
- if show:
- print('match head_keyword4')
- inner_table[i][j][1] = 1
- if row_col[0] in head_keyword5:
- if show:
- print('match head_keyword5')
- inner_table[i][j][1] = 0
- for key in head_keyword6:
- match = re.search(key, row_col[0])
- if match:
- if show:
- print('match head_keyword6')
- inner_table[i][j][1] = 0
- for key in head_keyword7:
- match = re.search(key+'$', row_col[0])
- if match and row_col[1] == 1:
- if show:
- print('match head_keyword7')
- inner_table[i][j][1] = 0
- if row_col[0] in head_keyword8 and row_col[1] == 0:
- if show:
- print('match head_keyword8')
- all_head_flag = 1
- for k in range(len(row)):
- if row[k][0] in ['', row_col[0]]:
- continue
- if row[k][1] == 0:
- print('row[k]', row[k])
- all_head_flag = 0
- break
- # print('all_head_flag', all_head_flag)
- if all_head_flag:
- inner_table[i][j][1] = 1
- return inner_table
- def repair_by_length(inner_table):
- for i in range(len(inner_table)):
- for j in range(len(inner_table[i])):
- if len(inner_table[i][j][0]) >= 30:
- inner_table[i][j][1] = 0
- return inner_table
- def repair_by_summation(inner_table):
- # 修复合计在中间的特殊情况
- if len(inner_table) >= 3 and len(inner_table[1]) == 2 \
- and inner_table[1][0][0] == '合计' and inner_table[1][1][0].endswith('%'):
- inner_table[1][0][1] = 0
- inner_table[1][1][1] = 0
- return inner_table
- def repair_by_rank(inner_table):
- if not inner_table or (inner_table and len(inner_table[0]) < 3):
- return inner_table
- for i in range(len(inner_table)):
- for j in range(len(inner_table[i])-2):
- if inner_table[i][j][0] in ['第一名'] and inner_table[i][j+1][0] in ['第二名'] and inner_table[i][j+2][0] in ['第三名']:
- inner_table[i][j][1] = 1
- inner_table[i][j+1][1] = 1
- inner_table[i][j+2][1] = 1
- return inner_table
- _inner_table = pre_process(_inner_table)
- compare_inner_table = copy.deepcopy(_inner_table)
- if show:
- print('table_head_repair_process1', show_row_index, _inner_table[show_row_index])
- _inner_table = repair_by_rank(_inner_table)
- if _inner_table != compare_inner_table:
- compare_inner_table = copy.deepcopy(_inner_table)
- log('table_head repair1.5 ' + str(docid))
- if show:
- print('table_head_repair_process1.5', show_row_index, _inner_table[show_row_index])
- _inner_table = repair_by_colon(_inner_table)
- if _inner_table != compare_inner_table:
- compare_inner_table = copy.deepcopy(_inner_table)
- log('table_head repair2 ' + str(docid))
- if show:
- print('table_head_repair_process2', show_row_index, _inner_table[show_row_index])
- _inner_table = repair_by_keywords(_inner_table)
- if _inner_table != compare_inner_table:
- compare_inner_table = copy.deepcopy(_inner_table)
- log('table_head repair3 ' + str(docid))
- if show:
- print('table_head_repair_process3', show_row_index, _inner_table[show_row_index])
- _inner_table = repair_by_tenderer(_inner_table)
- if _inner_table != compare_inner_table:
- compare_inner_table = copy.deepcopy(_inner_table)
- log('table_head repair4 ' + str(docid))
- if show:
- print('table_head_repair_process4', show_row_index, _inner_table[show_row_index])
- _inner_table = repair_by_duplicate(_inner_table)
- if _inner_table != compare_inner_table:
- compare_inner_table = copy.deepcopy(_inner_table)
- log('table_head repair5 ' + str(docid))
- if show:
- print('table_head_repair_process5', show_row_index, _inner_table[show_row_index])
- _inner_table = repair_by_around(_inner_table)
- if _inner_table != compare_inner_table:
- compare_inner_table = copy.deepcopy(_inner_table)
- log('table_head repair6 ' + str(docid))
- if show:
- print('table_head_repair_process6', show_row_index, _inner_table[show_row_index])
- _inner_table = repair_by_tenderer(_inner_table)
- if _inner_table != compare_inner_table:
- compare_inner_table = copy.deepcopy(_inner_table)
- log('table_head repair7 ' + str(docid))
- if show:
- print('table_head_repair_process7', show_row_index, _inner_table[show_row_index])
- _inner_table = repair_by_keywords(_inner_table)
- if _inner_table != compare_inner_table:
- compare_inner_table = copy.deepcopy(_inner_table)
- log('table_head repair8 ' + str(docid))
- if show:
- print('table_head_repair_process8', show_row_index, _inner_table[show_row_index])
- _inner_table = repair_by_length(_inner_table)
- if _inner_table != compare_inner_table:
- compare_inner_table = copy.deepcopy(_inner_table)
- print('table_head repair9 ' + str(docid))
- if show:
- print('table_head_repair_process9', show_row_index, _inner_table[show_row_index])
- _inner_table = repair_by_summation(_inner_table)
- if show:
- print('table_head_repair_process10', show_row_index, _inner_table[show_row_index])
- return _inner_table
- re_num = re.compile("[二三四五六七八九]十[一二三四五六七八九]?|十[一二三四五六七八九]|[一二三四五六七八九十]")
- num_dict = {
- "一": 1, "二": 2,
- "三": 3, "四": 4,
- "五": 5, "六": 6,
- "七": 7, "八": 8,
- "九": 9, "十": 10}
- # 一百以内的中文大写转换为数字
- def change2num(text):
- result_num = -1
- # text = text[:6]
- match = re_num.search(text)
- if match:
- _num = match.group()
- if num_dict.get(_num):
- return num_dict.get(_num)
- else:
- tenths = 1
- the_unit = 0
- num_split = _num.split("十")
- if num_dict.get(num_split[0]):
- tenths = num_dict.get(num_split[0])
- if num_dict.get(num_split[1]):
- the_unit = num_dict.get(num_split[1])
- result_num = tenths * 10 + the_unit
- elif re.search("\d{1,2}",text):
- _num = re.search("\d{1,2}",text).group()
- result_num = int(_num)
- return result_num
- #大纲分段处理
- def get_preprocessed_outline(soup):
- pattern_0 = re.compile("^(?:[二三四五六七八九]十[一二三四五六七八九]?|十[一二三四五六七八九]|[一二三四五六七八九十])[、.\.]")
- pattern_1 = re.compile("^[\((]?(?:[二三四五六七八九]十[一二三四五六七八九]?|十[一二三四五六七八九]|[一二三四五六七八九十])[\))]")
- pattern_2 = re.compile("^\d{1,2}[、.\.](?=[^\d]{1,2}|$)")
- pattern_3 = re.compile("^[\((]?\d{1,2}[\))]")
- pattern_list = [pattern_0, pattern_1, pattern_2, pattern_3]
- body = soup.find("body")
- if body == None:
- return soup # 修复 无body的报错 例子:264419050
- body_child = body.find_all(recursive=False)
- deal_part = body
- # print(body_child[0]['id'])
- if 'id' in body_child[0].attrs:
- if len(body_child) <= 2 and body_child[0]['id'] == 'pcontent':
- deal_part = body_child[0]
- if len(deal_part.find_all(recursive=False))>2:
- deal_part = deal_part.parent
- skip_tag = ['turntable', 'tbody', 'th', 'tr', 'td', 'table','thead','tfoot']
- for part in deal_part.find_all(recursive=False):
- # 查找解析文本的主干部分
- is_main_text = False
- through_text_num = 0
- while (not is_main_text and part.find_all(recursive=False)):
- while len(part.find_all(recursive=False)) == 1 and part.get_text(strip=True) == \
- part.find_all(recursive=False)[0].get_text(strip=True):
- part = part.find_all(recursive=False)[0]
- max_len = len(part.get_text(strip=True))
- is_main_text = True
- for t_part in part.find_all(recursive=False):
- if t_part.name not in skip_tag and t_part.get_text(strip=True)!="":
- through_text_num += 1
- if t_part.get_text(strip=True)!="" and len(t_part.get_text(strip=True))/max_len>=0.65:
- if t_part.name not in skip_tag:
- is_main_text = False
- part = t_part
- break
- else:
- while len(t_part.find_all(recursive=False)) == 1 and t_part.get_text(strip=True) == \
- t_part.find_all(recursive=False)[0].get_text(strip=True):
- t_part = t_part.find_all(recursive=False)[0]
- if through_text_num>2:
- is_table = True
- for _t_part in t_part.find_all(recursive=False):
- if _t_part.name not in skip_tag:
- is_table = False
- break
- if not is_table:
- is_main_text = False
- part = t_part
- break
- else:
- is_main_text = False
- part = t_part
- break
- is_find = False
- for _pattern in pattern_list:
- last_index = 0
- handle_list = []
- for _part in part.find_all(recursive=False):
- if _part.name not in skip_tag and _part.get_text(strip=True) != "":
- # print('text:', _part.get_text(strip=True))
- re_match = re.search(_pattern, _part.get_text(strip=True))
- if re_match:
- outline_index = change2num(re_match.group())
- if last_index < outline_index:
- # _part.insert_before("##split##")
- handle_list.append(_part)
- last_index = outline_index
- if len(handle_list)>1:
- is_find = True
- for _part in handle_list:
- _part.insert_before("##split##")
- if is_find:
- break
- # print(soup)
- return soup
- #数据清洗
- def segment(soup,final=True):
- # print("==")
- # print(soup)
- # print("====")
- #segList = ["tr","div","h1", "h2", "h3", "h4", "h5", "h6", "header"]
- subspaceList = ["td",'a',"span","p"]
- if soup.name in subspaceList:
- #判断有值叶子节点数
- _count = 0
- for child in soup.find_all(recursive=True):
- if child.get_text().strip()!="" and len(child.find_all())==0:
- _count += 1
- if _count<=1:
- text = soup.get_text()
- # 2020/11/24 大网站规则添加
- if 'title' in soup.attrs:
- if '...' in soup.get_text() and soup.get_text().strip()[:-3] in soup.attrs['title']:
- text = soup.attrs['title']
- _list = []
- for x in re.split("\s+",text):
- if x.strip()!="":
- _list.append(len(x))
- if len(_list)>0:
- _minLength = min(_list)
- if _minLength>2:
- _substr = ","
- else:
- _substr = ""
- else:
- _substr = ""
- text = text.replace("\r\n",",").replace("\n",",")
- text = re.sub("\s+",_substr,text)
- # text = re.sub("\s+","##space##",text)
- return text
- segList = ["title"]
- commaList = ["div","br","td","p","li","h1","h2","h3","h4","h5","h6"]
- #commaList = []
- spaceList = ["span"]
- tbodies = soup.find_all('tbody')
- if len(tbodies) == 0:
- tbodies = soup.find_all('table')
- # 递归遍历所有节点,插入符号
- for child in soup.find_all(recursive=True):
- # print(child.name,child.get_text())
- if child.name in segList:
- child.insert_after("。")
- if child.name in commaList:
- child.insert_after(",")
- # if child.name != "td" and re.match('[((][一二三四五六七八九十]+[))]|[一二三四五六七八九十]+\s*、', child.get_text().strip()): # 大纲前面用句号分割 20240930 注销,修复529501491关键词 三、中标供应商:(一)单位名称被分句
- # child.insert_before("。")
- # if child.name == 'div' and 'class' in child.attrs:
- # # 添加附件"attachment"标识
- # if "richTextFetch" in child['class']:
- # child.insert_before("##attachment##")
- # print(child.parent)
- # if child.name in subspaceList:
- # child.insert_before("#subs"+str(child.name)+"#")
- # child.insert_after("#sube"+str(child.name)+"#")
- # if child.name in spaceList:
- # child.insert_after(" ")
- text = str(soup.get_text())
- #替换英文冒号为中文冒号
- text = re.sub("(?<=[\u4e00-\u9fa5]):|:(?=[\u4e00-\u9fa5])",":",text)
- #替换为中文逗号
- text = re.sub("(?<=[\u4e00-\u9fa5]),|,(?=[\u4e00-\u9fa5])",",",text)
- #替换为中文分号
- text = re.sub("(?<=[\u4e00-\u9fa5]);|;(?=[\u4e00-\u9fa5])",";",text)
- # 感叹号替换为中文句号
- text = re.sub("(?<=[\u4e00-\u9fa5])[!!]|[!!](?=[\u4e00-\u9fa5])","。",text)
- #替换格式未识别的问号为" " ,update:2021/7/20
- text = re.sub("[?\?]{2,}|\n"," ",text)
- #替换"""为"“",否则导入deepdive出错
- # text = text.replace('"',"“").replace("\r","").replace("\n",",")
- text = text.replace('"',"“").replace("\r","").replace("\n","").replace("\\n","") #2022/1/4修复 非分段\n 替换为逗号造成 公司拆分 span \n南航\n上海\n分公司
- text = re.sub("( )+"," ",text) # 空白符替换
- # print('==1',text)
- # text = re.sub("\s{4,}",",",text)
- # 解决公告中的" "空格替换问题
- if re.search("\s{4,}",text):
- _text = ""
- for _sent in re.split("。+",text):
- for _sent2 in re.split(',+',_sent):
- for _sent3 in re.split(":+",_sent2):
- pre_t = ''
- for _t in re.split("\s{4,}",_sent3):
- if len(_t)<3 or len(pre_t)<3 or re.search('[^\w\s]$', pre_t): # 20240726 前文小于3字或以符合结尾的不加 避免乱加逗号 例:2) 申请人的资格要求
- _text += _t
- else:
- _text += ","+_t
- pre_t = _t
- _text += ":"
- _text = _text[:-1]
- _text += ","
- _text = _text[:-1]
- _text += "。"
- _text = _text[:-1]
- text = _text
- # print('==2',text)
- #替换标点
- #替换连续的标点
- if final:
- text = re.sub("##space##"," ",text)
- punc_pattern = "(?P<del>[。,;::,\s]+)"
- list_punc = re.findall(punc_pattern,text)
- list_punc.sort(key=lambda x:len(x),reverse=True)
- for punc_del in list_punc:
- if len(punc_del)>1:
- if len(punc_del.strip())>0:
- if ":" in punc_del.strip():
- if "。" in punc_del.strip():
- text = re.sub(punc_del, ":。", text)
- else:
- text = re.sub(punc_del,":",text)
- else:
- text = re.sub(punc_del,punc_del.strip()[0],text) #2021/12/09 修正由于某些标签后插入符号把原来符号替换
- else:
- text = re.sub(punc_del," ",text) # 多个空字符替换为一个空格(防止时间类连接),后面还有对空格处理
- #将连续的中文句号替换为一个
- # text_split = text.split("。")
- # text_split = [x for x in text_split if len(x)>0]
- # text = "。".join(text_split)
- text = re.sub('。+', '。', text).lstrip('。') # 20240703 修复上面的方法造成文末句号丢失问题。
- # #删除标签中的所有空格
- # for subs in subspaceList:
- # patten = "#subs"+str(subs)+"#(.*?)#sube"+str(subs)+"#"
- # while(True):
- # oneMatch = re.search(re.compile(patten),text)
- # if oneMatch is not None:
- # _match = oneMatch.group(1)
- # text = text.replace("#subs"+str(subs)+"#"+_match+"#sube"+str(subs)+"#",_match)
- # else:
- # break
- # text过大报错
- LOOP_LEN = 10000
- LOOP_BEGIN = 0
- _text = ""
- if len(text)<10000000:
- while(LOOP_BEGIN<len(text)):
- _text += re.sub(")",")",re.sub("(","(",re.sub("\s(?!\d{1,2}[::]\d{2}|\d{1,2}[点时])","",text[LOOP_BEGIN:LOOP_BEGIN+LOOP_LEN])))
- LOOP_BEGIN += LOOP_LEN
- text = _text
- # 附件标识前修改为句号,避免正文和附件内容混合在一起
- text = re.sub("[^。](?=##attachment##)","。",text)
- text = re.sub("[^。](?=##attachment_begin##)","。",text)
- text = re.sub("[^。](?=##attachment_end##)","。",text)
- text = re.sub("##attachment_begin##。","##attachment_begin##",text)
- text = re.sub("##attachment_end##。","##attachment_end##",text)
- return text
- '''
- #数据清洗
- def segment(soup):
- segList = ["title"]
- commaList = ["p","div","h1", "h2", "h3", "h4", "h5", "h6", "header", "dl", "ul", "label"]
- spaceList = ["span"]
- tbodies = soup.find_all('tbody')
- if len(tbodies) == 0:
- tbodies = soup.find_all('table')
- # 递归遍历所有节点,插入符号
- for child in soup.find_all(recursive=True):
- if child.name == 'br':
- child.insert_before(',')
- child_text = re.sub('\s', '', child.get_text())
- if child_text == '' or child_text[-1] in ['。',',',':',';']:
- continue
- if child.name in segList:
- child.insert_after("。")
- if child.name in commaList:
- if len(child_text)>3 and len(child_text) <50: # 先判断是否字数少于50,成立加逗号,否则加句号
- child.insert_after(",")
- elif len(child_text) >=50:
- child.insert_after("。")
- #if child.name in spaceList:
- #child.insert_after(" ")
- text = str(soup.get_text())
- text = re.sub("\s{5,}",",",text)
- text = text.replace('"',"“").replace("\r","").replace("\n",",")
- #替换"""为"“",否则导入deepdive出错
- text = text.replace('"',"“")
- #text = text.replace('"',"“").replace("\r","").replace("\n","")
-
- #删除所有空格
- text = re.sub("\s+","#nbsp#",text)
- text_list = text.split('#nbsp#')
- new_text = ''
- for i in range(len(text_list)-1):
- if text_list[i] == '' or text_list[i][-1] in [',','。',';',':']:
- new_text += text_list[i]
- elif re.findall('([一二三四五六七八九]、)', text_list[i+1][:4]) != []:
- new_text += text_list[i] + '。'
- elif re.findall('([0-9]、)', text_list[i+1][:4]) != []:
- new_text += text_list[i] + ';'
- elif text_list[i].isdigit() and text_list[i+1].isdigit():
- new_text += text_list[i] + ' '
- elif text_list[i][-1] in ['-',':','(',')','/','(',')','——','年','月','日','时','分','¥'] or text_list[i+1][0] in ['-',':','(',')','/','(',')','——','年','月','日','时','分','元','万元']:
- new_text += text_list[i]
- elif len(text_list[i]) >= 3 and len(text_list[i+1]) >= 3:
- new_text += text_list[i] + ','
- else:
- new_text += text_list[i]
- new_text += text_list[-1]
- text = new_text
- #替换英文冒号为中文冒号
- text = re.sub("(?<=[\u4e00-\u9fa5]):|:(?=[\u4e00-\u9fa5])",":",text)
- #替换为中文逗号
- text = re.sub("(?<=[\u4e00-\u9fa5]),|,(?=[\u4e00-\u9fa5])",",",text)
- #替换为中文分号
- text = re.sub("(?<=[\u4e00-\u9fa5]);|;(?=[\u4e00-\u9fa5])",";",text)
-
- #替换标点
- while(True):
- #替换连续的标点
- punc = re.search(",(?P<punc>:|。|,|;)\s*",text)
- if punc is not None:
- text = re.sub(","+punc.group("punc")+"\s*",punc.group("punc"),text)
-
- punc = re.search("(?P<punc>:|。|,|;)\s*,",text)
- if punc is not None:
- text = re.sub(punc.group("punc")+"\s*,",punc.group("punc"),text)
- else:
- #替换标点之后的空格
- punc = re.search("(?P<punc>:|。|,|;)\s+",text)
- if punc is not None:
- text = re.sub(punc.group("punc")+"\s+",punc.group("punc"),text)
- else:
- break
- #将连续的中文句号替换为一个
- text_split = text.split("。")
- text_split = [x for x in text_split if len(x)>0]
- text = "。".join(text_split)
- #替换中文括号为英文括号
- text = re.sub("(","(",text)
- text = re.sub(")",")",text)
- return text
- '''
- #连续实体合并(弃用)
- def union_ner(list_ner):
- result_list = []
- union_index = []
- union_index_set = set()
- for i in range(len(list_ner)-1):
- if len(set([str(list_ner[i][2]),str(list_ner[i+1][2])])&set(["org","company"]))==2:
- if list_ner[i][1]-list_ner[i+1][0]==1:
- union_index_set.add(i)
- union_index_set.add(i+1)
- union_index.append((i,i+1))
- for i in range(len(list_ner)):
- if i not in union_index_set:
- result_list.append(list_ner[i])
- for item in union_index:
- #print(str(list_ner[item[0]][3])+str(list_ner[item[1]][3]))
- 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])))
- return result_list
-
- # def get_preprocessed(articles,useselffool=False):
- # '''
- # @summary:预处理步骤,NLP处理、实体识别
- # @param:
- # articles:待处理的文章list [[id,source,jointime,doc_id,title]]
- # @return:list of articles,list of each article of sentences,list of each article of entitys
- # '''
- # list_articles = []
- # list_sentences = []
- # list_entitys = []
- # cost_time = dict()
- # for article in articles:
- # list_sentences_temp = []
- # list_entitys_temp = []
- # doc_id = article[0]
- # sourceContent = article[1]
- # _send_doc_id = article[3]
- # _title = article[4]
- # #表格处理
- # key_preprocess = "tableToText"
- # start_time = time.time()
- # article_processed = segment(tableToText(BeautifulSoup(sourceContent,"lxml")))
- #
- # # log(article_processed)
- #
- # if key_preprocess not in cost_time:
- # cost_time[key_preprocess] = 0
- # cost_time[key_preprocess] += time.time()-start_time
- #
- # #article_processed = article[1]
- # list_articles.append(Article(doc_id,article_processed,sourceContent,_send_doc_id,_title))
- # #nlp处理
- # if article_processed is not None and len(article_processed)!=0:
- # split_patten = "。"
- # sentences = []
- # _begin = 0
- # for _iter in re.finditer(split_patten,article_processed):
- # sentences.append(article_processed[_begin:_iter.span()[1]])
- # _begin = _iter.span()[1]
- # sentences.append(article_processed[_begin:])
- #
- # lemmas = []
- # doc_offsets = []
- # dep_types = []
- # dep_tokens = []
- #
- # time1 = time.time()
- #
- # '''
- # tokens_all = fool.cut(sentences)
- # #pos_all = fool.LEXICAL_ANALYSER.pos(tokens_all)
- # #ner_tag_all = fool.LEXICAL_ANALYSER.ner_labels(sentences,tokens_all)
- # ner_entitys_all = fool.ner(sentences)
- # '''
- # #限流执行
- # key_nerToken = "nerToken"
- # start_time = time.time()
- # tokens_all,ner_entitys_all = getTokensAndNers(sentences,useselffool=useselffool)
- # if key_nerToken not in cost_time:
- # cost_time[key_nerToken] = 0
- # cost_time[key_nerToken] += time.time()-start_time
- #
- #
- # for sentence_index in range(len(sentences)):
- #
- #
- #
- # list_sentence_entitys = []
- # sentence_text = sentences[sentence_index]
- # tokens = tokens_all[sentence_index]
- #
- # list_tokenbegin = []
- # begin = 0
- # for i in range(0,len(tokens)):
- # list_tokenbegin.append(begin)
- # begin += len(str(tokens[i]))
- # list_tokenbegin.append(begin+1)
- # #pos_tag = pos_all[sentence_index]
- # pos_tag = ""
- #
- # ner_entitys = ner_entitys_all[sentence_index]
- #
- # 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))
- #
- # #识别package
- #
- #
- # #识别实体
- # for ner_entity in ner_entitys:
- # begin_index_temp = ner_entity[0]
- # end_index_temp = ner_entity[1]
- # entity_type = ner_entity[2]
- # entity_text = ner_entity[3]
- #
- # for j in range(len(list_tokenbegin)):
- # if list_tokenbegin[j]==begin_index_temp:
- # begin_index = j
- # break
- # elif list_tokenbegin[j]>begin_index_temp:
- # begin_index = j-1
- # break
- # begin_index_temp += len(str(entity_text))
- # for j in range(begin_index,len(list_tokenbegin)):
- # if list_tokenbegin[j]>=begin_index_temp:
- # end_index = j-1
- # break
- # entity_id = "%s_%d_%d_%d"%(doc_id,sentence_index,begin_index,end_index)
- #
- # #去掉标点符号
- # entity_text = re.sub("[,,。:]","",entity_text)
- # 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))
- #
- #
- # #使用正则识别金额
- # entity_type = "money"
- #
- # #money_patten_str = "(([1-9][\d,,]*(?:\.\d+)?[百千万亿]?[\(\)()元整]+)|([零壹贰叁肆伍陆柒捌玖拾佰仟萬億十百千万亿元角分]{3,})|(?:[¥¥]+,?|报价|标价)[(\(]?([万])?元?[)\)]?[::]?.{,7}?([1-9][\d,,]*(?:\.\d+)?(?:,?)[百千万亿]?)|([1-9][\d,,]*(?:\.\d+)?(?:,?)[百千万亿]?)[\((]?([万元]{1,2}))*"
- #
- # list_money_pattern = {"cn":"(()()([零壹贰叁肆伍陆柒捌玖拾佰仟萬億十百千万亿元角分]{3,})())*",
- # "key_word":"((?:[¥¥]+,?|[报标限]价|金额)(?:[(\(]?\s*([万元]*)\s*[)\)]?)\s*[::]?(\s*[^壹贰叁肆伍陆柒捌玖拾佰仟萬億分]{,7}?)([0-9][\d,,]*(?:\.\d+)?(?:,?)[百千万亿元]*)())*",
- # "front_m":"((?:[(\(]?\s*([万元]+)\s*[)\)])\s*[::]?(\s*[^壹贰叁肆伍陆柒捌玖拾佰仟萬億分]{,7}?)([0-9][\d,,]*(?:\.\d+)?(?:,?)[百千万亿元]*)())*",
- # "behind_m":"(()()([0-9][\d,,]*(?:\.\d+)?(?:,?)[百千万亿]*)[\((]?([万元]+)[\))]?)*"}
- #
- # set_begin = set()
- # for pattern_key in list_money_pattern.keys():
- # pattern = re.compile(list_money_pattern[pattern_key])
- # all_match = re.findall(pattern, sentence_text)
- # index = 0
- # for i in range(len(all_match)):
- # if len(all_match[i][0])>0:
- # # print("===",all_match[i])
- # #print(all_match[i][0])
- # unit = ""
- # entity_text = all_match[i][3]
- # if pattern_key in ["key_word","front_m"]:
- # unit = all_match[i][1]
- # else:
- # unit = all_match[i][4]
- # if entity_text.find("元")>=0:
- # unit = ""
- #
- # index += len(all_match[i][0])-len(entity_text)-len(all_match[i][4])#-len(all_match[i][1])-len(all_match[i][2])#整个提出来的作为实体->数字部分作为整体,否则会丢失特征
- #
- # begin_index_temp = index
- # for j in range(len(list_tokenbegin)):
- # if list_tokenbegin[j]==index:
- # begin_index = j
- # break
- # elif list_tokenbegin[j]>index:
- # begin_index = j-1
- # break
- # index += len(str(entity_text))+len(all_match[i][4])#+len(all_match[i][2])+len(all_match[i][1])#整个提出来的作为实体
- # end_index_temp = index
- # #index += len(str(all_match[i][0]))
- # for j in range(begin_index,len(list_tokenbegin)):
- # if list_tokenbegin[j]>=index:
- # end_index = j-1
- # break
- # entity_id = "%s_%d_%d_%d"%(doc_id,sentence_index,begin_index,end_index)
- #
- #
- # entity_text = re.sub("[^0-9.零壹贰叁肆伍陆柒捌玖拾佰仟萬億十百千万亿元角分]","",entity_text)
- # if len(unit)>0:
- # entity_text = str(getUnifyMoney(entity_text)*getMultipleFactor(unit[0]))
- # else:
- # entity_text = str(getUnifyMoney(entity_text))
- #
- # _exists = False
- # for item in list_sentence_entitys:
- # if item.entity_id==entity_id and item.entity_type==entity_type:
- # _exists = True
- # if not _exists:
- # if float(entity_text)>10:
- # 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))
- #
- # else:
- # index += 1
- #
- # list_sentence_entitys.sort(key=lambda x:x.begin_index)
- # list_entitys_temp = list_entitys_temp+list_sentence_entitys
- # list_sentences.append(list_sentences_temp)
- # list_entitys.append(list_entitys_temp)
- # return list_articles,list_sentences,list_entitys,cost_time
- def get_preprocessed(articles, useselffool=False):
- '''
- @summary:预处理步骤,NLP处理、实体识别
- @param:
- articles:待处理的文章list [[id,source,jointime,doc_id,title]]
- @return:list of articles,list of each article of sentences,list of each article of entitys
- '''
- cost_time = dict()
- list_articles = get_preprocessed_article(articles,cost_time)
- list_sentences,list_outlines = get_preprocessed_sentences(list_articles,True,cost_time)
- list_entitys = get_preprocessed_entitys(list_sentences,True,cost_time)
- calibrateEnterprise(list_articles,list_sentences,list_entitys)
- return list_articles,list_sentences,list_entitys,list_outlines,cost_time
- def special_treatment(sourceContent, web_source_no):
- try:
- if web_source_no == 'DX000202-1':
- ser = re.search('中标供应商及中标金额:【(([\w()]{5,20}-[\d,.]+,)+)】', sourceContent)
- if ser:
- new = ""
- l = ser.group(1).split(',')
- for i in range(len(l)):
- it = l[i]
- if '-' in it:
- role, money = it.split('-')
- new += '标段%d, 中标供应商: ' % (i + 1) + role + ',中标金额:' + money + '。'
- sourceContent = sourceContent.replace(ser.group(0), new, 1)
- elif web_source_no == '00753-14':
- body = sourceContent.find("body")
- body_child = body.find_all(recursive=False)
- pcontent = body
- if 'id' in body_child[0].attrs:
- if len(body_child) <= 2 and body_child[0]['id'] == 'pcontent':
- pcontent = body_child[0]
- # pcontent = sourceContent.find("div", id="pcontent")
- pcontent = pcontent.find_all(recursive=False)[0]
- first_table = None
- for idx in range(len(pcontent.find_all(recursive=False))):
- t_part = pcontent.find_all(recursive=False)[idx]
- if t_part.name != "table":
- break
- if idx == 0:
- first_table = t_part
- else:
- for _tr in t_part.find("tbody").find_all(recursive=False):
- first_table.find("tbody").append(_tr)
- t_part.clear()
- elif web_source_no == 'DX008357-11':
- body = sourceContent.find("body")
- body_child = body.find_all(recursive=False)
- pcontent = body
- if 'id' in body_child[0].attrs:
- if len(body_child) <= 2 and body_child[0]['id'] == 'pcontent':
- pcontent = body_child[0]
- # pcontent = sourceContent.find("div", id="pcontent")
- pcontent = pcontent.find_all(recursive=False)[0]
- error_table = []
- is_error_table = False
- for part in pcontent.find_all(recursive=False):
- if is_error_table:
- if part.name == "table":
- error_table.append(part)
- else:
- break
- if part.name == "div" and part.get_text(strip=True) == "中标候选单位:":
- is_error_table = True
- first_table = None
- for idx in range(len(error_table)):
- t_part = error_table[idx]
- # if t_part.name != "table":
- # break
- if idx == 0:
- for _tr in t_part.find("tbody").find_all(recursive=False):
- if _tr.get_text(strip=True) == "":
- _tr.decompose()
- first_table = t_part
- else:
- for _tr in t_part.find("tbody").find_all(recursive=False):
- if _tr.get_text(strip=True) != "":
- first_table.find("tbody").append(_tr)
- t_part.clear()
- elif web_source_no == '18021-2':
- body = sourceContent.find("body")
- body_child = body.find_all(recursive=False)
- pcontent = body
- if 'id' in body_child[0].attrs:
- if len(body_child) <= 2 and body_child[0]['id'] == 'pcontent':
- pcontent = body_child[0]
- # pcontent = sourceContent.find("div", id="pcontent")
- td = pcontent.find_all("td")
- for _td in td:
- if str(_td.string).strip() == "报价金额":
- _td.string = "单价"
- elif web_source_no == '13740-2':
- # “xxx成为成交供应商”
- re_match = re.search("[^,。]+成为[^,。]*成交供应商", sourceContent)
- if re_match:
- sourceContent = sourceContent.replace(re_match.group(), "成交人:" + re_match.group())
- elif web_source_no == '03786-10':
- ser1 = re.search('中标价:([\d,.]+)', sourceContent)
- ser2 = re.search('合同金额[((]万元[))]:([\d,.]+)', sourceContent)
- if ser1 and ser2:
- m1 = ser1.group(1).replace(',', '')
- m2 = ser2.group(1).replace(',', '')
- if float(m1) < 100000 and (m1.split('.')[0] == m2.split('.')[0] or m2 == '0'):
- new = '中标价(万元):' + m1
- sourceContent = sourceContent.replace(ser1.group(0), new, 1)
- elif web_source_no=='00076-4':
- ser = re.search('主要标的数量:([0-9一]+)\w{,3},主要标的单价:([\d,.]+)元?,合同金额:(.00),', sourceContent)
- if ser:
- num = ser.group(1).replace('一', '1')
- try:
- num = 1 if num == '0' else num
- unit_price = ser.group(2).replace(',', '')
- total_price = str(int(num) * float(unit_price))
- new = '合同金额:' + total_price
- sourceContent = sourceContent.replace('合同金额:.00', new, 1)
- except Exception as e:
- log('preprocessing.py special_treatment exception')
- elif web_source_no=='DX000105-2':
- if re.search("成交公示", sourceContent) and re.search(',投标人:', sourceContent) and re.search(',成交人:', sourceContent)==None:
- sourceContent = sourceContent.replace(',投标人:', ',成交人:')
- elif web_source_no in ['03795-1', '03795-2']:
- if re.search('中标单位如下', sourceContent) and re.search(',投标人:', sourceContent) and re.search(',中标人:', sourceContent)==None:
- sourceContent = sourceContent.replace(',投标人:', ',中标人:')
- elif web_source_no in ['04080-3', '04080-4']:
- ser = re.search('合同金额:([0-9,]+.[0-9]{3,})(.{,4})', sourceContent)
- if ser and '万' not in ser.group(2):
- sourceContent = sourceContent.replace('合同金额:', '合同金额(万元):')
- elif web_source_no=='03761-3':
- ser = re.search('中标价,([0-9]+)[.0-9]*%', sourceContent)
- if ser and int(ser.group(1))>100:
- sourceContent = sourceContent.replace(ser.group(0), ser.group(0)[:-1]+'元')
- elif web_source_no=='00695-7':
- ser = re.search('支付金额:', sourceContent)
- if ser:
- sourceContent = sourceContent.replace('支付金额:', '合同金额:')
- elif web_source_no=='00811-8':
- if re.search('是否中标:是', sourceContent) and re.search('排名:\d,', sourceContent):
- sourceContent = re.sub('排名:\d,', '候选', sourceContent)
- elif web_source_no=='DX000726-6':
- sourceContent = re.sub('卖方[::\s]+宝山钢铁股份有限公司', '招标单位:宝山钢铁股份有限公司', sourceContent)
- elif web_source_no=='DX008791-1':
- sourceContent = re.sub('收货单位:', '最终用户:', sourceContent)
- elif web_source_no=='DX011971':
- sourceContent = re.sub('公司主体:', '业主单位:', sourceContent)
- return sourceContent
- except Exception as e:
- log('特殊数据源: %s 预处理特别修改抛出异常: %s'%(web_source_no, e))
- return sourceContent
- def article_limit(soup,limit_words=30000):
- sub_space = re.compile("\s+")
- def soup_limit(_soup,_count,max_count=30000,max_gap=500):
- """
- :param _soup: soup
- :param _count: 当前字数
- :param max_count: 字数最大限制
- :param max_gap: 超过限制后的最大误差
- :return:
- """
- _gap = _count - max_count
- _is_skip = False
- next_soup = None
- # 跳过层级结构为1的标签,向下取值
- while len(_soup.find_all(recursive=False)) == 1 and \
- _soup.get_text(strip=True) == _soup.find_all(recursive=False)[0].get_text(strip=True):
- _soup = _soup.find_all(recursive=False)[0]
- # 无结构的纯文本直接取值
- if len(_soup.find_all(recursive=False)) == 0:
- _soup.string = str(_soup.get_text())[:max_count-_count]
- _count += len(re.sub(sub_space, "", _soup.string))
- _gap = _count - max_count
- next_soup = None
- else:
- for _soup_part in _soup.find_all(recursive=False):
- if not _is_skip:
- _count += len(re.sub(sub_space, "", _soup_part.get_text()))
- if _count >= max_count:
- _gap = _count - max_count
- if _gap <= max_gap:
- _is_skip = True
- else:
- _is_skip = True
- next_soup = _soup_part
- _count -= len(re.sub(sub_space, "", _soup_part.get_text()))
- continue
- else:
- _soup_part.decompose()
- return _count,_gap,next_soup
- text_count = 0
- have_attachment = False
- attachment_part = None
- for child in soup.find_all(recursive=True):
- if child.name == 'div' and 'class' in child.attrs:
- if "richTextFetch" in child['class']:
- child.insert_before("##attachment##。") # 句号分开,避免项目名称等提取
- attachment_part = child
- have_attachment = True
- break
- if not have_attachment:
- # 无附件,通过get_text()方法与limit_words大小判断是否要限制字数
- if len(re.sub(sub_space, "", soup.get_text())) > limit_words:
- text_count,gap,n_soup = soup_limit(soup,text_count,max_count=limit_words,max_gap=1000)
- while n_soup:
- text_count, gap, n_soup = soup_limit(n_soup, text_count, max_count=limit_words, max_gap=1000)
- else:
- # 有附件
- _text = re.sub(sub_space, "", soup.get_text())
- _text_split = _text.split("##attachment##")
- # 正文部分
- if len(_text_split[0])>limit_words:
- main_soup = attachment_part.parent
- main_text = main_soup.find_all(recursive=False)[0]
- text_count, gap, n_soup = soup_limit(main_text, text_count, max_count=limit_words, max_gap=1000)
- while n_soup:
- text_count, gap, n_soup = soup_limit(n_soup, text_count, max_count=limit_words, max_gap=1000)
- # 附件部分
- if len(_text_split[1])>limit_words:
- # attachment_html纯文本,无子结构
- if len(attachment_part.find_all(recursive=False))==0:
- attachment_part.string = str(attachment_part.get_text())[:limit_words]
- else:
- attachment_text_nums = 0
- attachment_skip = False
- for part in attachment_part.find_all(recursive=False):
- if not attachment_skip:
- if part.name == 'div' and 'filemd5' in part.attrs:
- for p_part in part.find_all(recursive=False):
- last_attachment_text_nums = attachment_text_nums
- attachment_text_nums = attachment_text_nums + len(re.sub(sub_space, "", p_part.get_text()))
- if not attachment_skip:
- if attachment_text_nums >= limit_words:
- p_part.string = str(p_part.get_text())[:limit_words - last_attachment_text_nums]
- attachment_skip = True
- else:
- p_part.decompose()
- # attachment_text_nums, gap, n_part = soup_limit(part, attachment_text_nums,
- # max_count=limit_words,max_gap=1000)
- # while n_part:
- # attachment_text_nums, gap, n_part = soup_limit(n_part, attachment_text_nums,
- # max_count=limit_words,max_gap=1000)
- # print(attachment_text_nums)
- else:
- last_attachment_text_nums = attachment_text_nums
- attachment_text_nums = attachment_text_nums + len(re.sub(sub_space, "", part.get_text()))
- if attachment_text_nums>=limit_words and not attachment_skip:
- part.string = str(part.get_text())[:limit_words-last_attachment_text_nums]
- attachment_skip = True
- else:
- part.decompose()
- return soup
- def attachment_filelink(soup):
- have_attachment = False
- attachment_part = None
- for child in soup.find_all(recursive=True):
- if child.name == 'div' and 'class' in child.attrs:
- if "richTextFetch" in child['class']:
- attachment_part = child
- have_attachment = True
- break
- if not have_attachment:
- return soup
- else:
- # 附件类型:图片、表格
- attachment_type = re.compile("\.(?:png|jpg|jpeg|tif|bmp|xlsx|xls)$")
- attachment_dict = dict()
- for _attachment in attachment_part.find_all(recursive=False):
- if _attachment.name == 'div' and 'filemd5' in _attachment.attrs:
- # print('filemd5',_attachment['filemd5'])
- attachment_dict[_attachment['filemd5']] = _attachment
- # print(attachment_dict)
- for child in soup.find_all(recursive=True):
- if child.name == 'div' and 'class' in child.attrs:
- if "richTextFetch" in child['class']:
- break
- if "filelink" in child.attrs and child['filelink'] in attachment_dict:
- if re.search(attachment_type,str(child.string).strip()) or \
- ('original' in child.attrs and re.search(attachment_type,str(child['original']).strip())) or \
- ('href' in child.attrs and re.search(attachment_type,str(child['href']).strip())):
- # 附件插入正文标识
- child.insert_before("。##attachment_begin##")
- child.insert_after("。##attachment_end##")
- child.replace_with(attachment_dict[child['filelink']])
- # print('格式化输出',soup.prettify())
- return soup
- def del_achievement(text):
- if re.search('中标|成交|入围|结果|评标|开标|候选人', text[:500]) == None or re.search('业绩', text) == None:
- return text
- p0 = '[,。;]((\d{1,2})|\d{1,2}、)[\w、]{,8}:|((\d{1,2})|\d{1,2}、)|。' # 例子 264392818
- p1 = '业绩[:,](\d、[-\w()、]{6,30}(工程|项目|勘察|设计|施工|监理|总承包|采购|更新)[\w()]{,10}[,;])+' # 例子 257717618
- p2 = '(类似业绩情况:|业绩:)(\w{,20}:)?(((\d)|\d、)项目名称:[-\w(),;、\d\s:]{5,100}[;。])+' # 例子 264345826
- p3 = '(投标|类似|(类似)?项目|合格|有效|企业|工程)?业绩(名称|信息|\d)?:(项目名称:)?[-\w()、]{6,50}(项目|工程|勘察|设计|施工|监理|总承包|采购|更新)'
- l = []
- tmp = []
- for it in re.finditer(p0, text):
- if it.group(0)[-3:] in ['业绩:', '荣誉:']:
- if tmp != []:
- del_text = text[tmp[0]:it.start()]
- l.append(del_text)
- tmp = []
- tmp.append(it.start())
- elif tmp != []:
- del_text = text[tmp[0]:it.start()]
- l.append(del_text)
- tmp = []
- if tmp != []:
- del_text = text[tmp[0]:]
- l.append(del_text)
- for del_text in l:
- text = text.replace(del_text, '')
- # print('删除业绩信息:', del_text)
- for rs in re.finditer(p1, text):
- # print('删除业绩信息:', rs.group(0))
- text = text.replace(rs.group(0), '')
- for rs in re.finditer(p2, text):
- # print('删除业绩信息:', rs.group(0))
- text = text.replace(rs.group(0), '')
- for rs in re.finditer(p3, text):
- # print('删除业绩信息:', rs.group(0))
- text = text.replace(rs.group(0), '')
- return text
- def split_header(soup):
- '''
- 处理 空格分割多个表头的情况 : 主要标的名称 规格型号(或服务要求) 主要标的数量 主要标的单价 合同金额(万元)
- :param soup: bs4 soup 对象
- :return:
- '''
- header = []
- attrs = []
- flag = 0
- tag = None
- for p in soup.find_all('p'):
- text = p.get_text()
- if re.search('主要标的数量\s+主要标的单价((万?元))?\s+合同金额', text):
- header = re.split('\s{3,}', text) if re.search('\s{3,}', text) else re.split('\s+', text)
- flag = 1
- tag = p
- tag.string = ''
- continue
- if flag:
- attrs = re.split('\s{3,}', text) if re.search('\s{3,}', text) else re.split('\s+', text)
- if header and len(header) == len(attrs) and tag:
- s = ""
- for head, attr in zip(header, attrs):
- s += head + ':' + attr + ','
- # tag.string = s
- # p.extract()
- p.string = s
- else:
- break
- def get_preprocessed_article(articles,cost_time = dict(),useselffool=True):
- '''
- :param articles: 待处理的article source html
- :param useselffool: 是否使用selffool
- :return: list_articles
- '''
- list_articles = []
- for article in articles:
- doc_id = article[0]
- sourceContent = article[1]
- sourceContent_raw = article[1] # 原始html数据,fingerprint计算MD5用
- sourceContent = re.sub("<html>|</html>|<body>|</body>","",sourceContent)
- sourceContent = re.sub("##attachment##","",sourceContent)
- sourceContent = sourceContent.replace('<br/>', '<br>')
- sourceContent = re.sub("<br>(\s{0,}<br>)+","<br>",sourceContent)
- # for br_match in re.findall("[^>]+?<br>",sourceContent):
- # _new = re.sub("<br>","",br_match)
- # # <br>标签替换为<p>标签
- # if not re.search("^\s+$",_new):
- # _new = '<p>'+_new + '</p>'
- # # print(br_match,_new)
- # sourceContent = sourceContent.replace(br_match,_new,1)
- _send_doc_id = article[3]
- _title = article[4]
- _title_raw = article[4]
- page_time = article[5]
- web_source_no = article[6]
- '''特别数据源对 html 做特别修改'''
- if web_source_no in ['DX000202-1']:
- sourceContent = special_treatment(sourceContent, web_source_no)
- #表格处理
- key_preprocess = "tableToText"
- start_time = time.time()
- # article_processed = tableToText(BeautifulSoup(sourceContent,"lxml"))
- article_processed = BeautifulSoup(sourceContent,"lxml")
- if re.search('主要标的数量( |\s)+主要标的单价((万?元))?( |\s)+合同金额', sourceContent): #处理 空格分割多个表头的情况
- split_header(article_processed)
- '''表格业绩内容删除'''
- del_tabel_achievement(article_processed)
- '''特别数据源对 BeautifulSoup(html) 做特别修改'''
- if web_source_no in ["00753-14","DX008357-11","18021-2"]:
- article_processed = special_treatment(article_processed, web_source_no)
- for _soup in article_processed.descendants:
- # 识别无标签文本,添加<span>标签
- if not _soup.name and not _soup.parent.string and _soup.string.strip()!="":
- # print(_soup.parent.string,_soup.string.strip())
- _soup.wrap(article_processed.new_tag("span"))
- # print(article_processed)
- # 正文和附件内容限制字数30000
- article_processed = article_limit(article_processed, limit_words=30000)
- # 把每个附件识别对应的html放回原来出现的位置
- article_processed = attachment_filelink(article_processed)
- article_processed = get_preprocessed_outline(article_processed)
- # print('article_processed')
- article_processed = tableToText(article_processed)
- # print(article_processed)
- article_processed = segment(article_processed)
- article_processed = article_processed.replace('(', '(').replace(')', ')') #2022/8/10 统一为中文括号
- article_processed = article_processed.replace('侯选人', '候选人') #2024/09/03 修复错别字避免预测错误。
- article_processed = article_processed.replace('人选人', '入选人') #2024/09/03 修复错别字避免预测错误。
- article_processed = article_processed.replace('⺠', '民') # 2025/02/17 修复错别字 例:连云港市第一人⺠医院。
- # article_processed = article_processed.replace(':', ':') #2023/1/5 统一为中文冒号
- article_processed = re.sub("(?<=[\u4e00-\u9fa5]):|:(?=[\u4e00-\u9fa5])", ":", article_processed)
- article_processed = article_processed.replace('.','.').replace('-', '-') # 2021/12/01 修正OCR识别PDF小数点错误问题
- article_processed = article_processed.replace('报价限价', '招标限价') #2021/12/17 由于报价限价预测为中投标金额所以修改
- article_processed = article_processed.replace('成交工程价款', '成交工程价') # 2021/12/21 修正为中标价
- article_processed = re.sub('任务(?=编号[::])', '项目',article_processed) # 2022/08/10 修正为项目编号
- article_processed = article_processed.replace('招标(建设)单位', '招标单位') #2022/8/10 修正预测不到表达
- # article_processed = re.sub("采购商(?=[^\u4e00-\u9fa5]|名称)", "招标人", article_processed) # 20250227注销,避免588296281 03338-7 始兴县人民政府 成交信息:采购商名称: 其实是中标人
- article_processed = re.sub('(招标|采购)人(概况|信息):?[,。]', '采购人信息:', article_processed) # 2022/8/10统一表达
- article_processed = article_processed.replace('\(%)', '') # 中标(成交)金额(元)\(%):498888.00, 处理 江西省政府采购网 金额特殊问题
- article_processed = re.sub('金额:?((可填写下浮率?、折扣率?或费率|拟签含税总单价总计|[^万元()\d]{8,20})))?:?', '金额:', article_processed) # 中标(成交)金额:(可填写下浮率、折扣率或费率):29.3万元 金额特殊问题 例:530377517
- article_processed = re.sub('(不?含(可抵扣增值|\w{,8})税)', '', article_processed) # 120637247 投标报价(元),(含可抵扣增值税):277,560.00。
- article_processed = re.sub('供应商的?(名称[及其、]{1,2}地址|联系方式:名称)', '供应商名称', article_processed) # 18889217, 84422177
- article_processed = re.sub(',最高有效报价者:', ',中标人名称:', article_processed) # 224678159 # 2023/7/4 四川站源特殊中标修改
- article_processed = re.sub(',最高有效报价:', ',投标报价:', article_processed) # 224678159 # 2023/7/4 四川站源特殊中标修改
- article_processed = re.sub('备选中标人', '第二候选人', article_processed) # 341344142 # 2023/7/17 特殊表达修改
- article_processed = re.sub('例:建设银行(甲方全称)', ' ', article_processed) # 2024/06/12 特殊表达修改 修改 481513912 金采网 附件模板导致错误提取招标人
- article_processed = re.sub('^[,,.。;;、]+', '', article_processed)
- article_processed = re.sub('资,金', '资金', article_processed)
- article_processed = re.sub('金,额', '金额', article_processed)
- article_processed = re.sub('存,款', '存款', article_processed)
- if web_source_no.startswith('DX002756-'):
- article_processed = re.sub('状态:(进行中|已结束)单位', ',项目单位', article_processed) # 376225646
- if web_source_no.startswith('DX006116-') and re.search('结果公告如下:.{5,50},单位名称:', article_processed): # 2023/11/20 特殊处理 381591924 381592533 这种提取不到情况
- article_processed = re.sub(',单位名称:', ',供应商名称:', article_processed)
- ser = re.search('(采购|招标|比选)人(名称)?/(采购|招标|比选)?代理机构(名称)?:(?P<tenderee>[\w()]{4,25}(/[\w()]{4,25})?)/(?P<agency>[\w()]{4,25})[,。]', article_processed)
- if ser:
- article_processed = article_processed.replace(ser.group(0), '采购人名称:%s,采购代理机构名称:%s,' % (ser.group('tenderee'), ser.group('agency')))
- ser2 = re.search('(采购|招标)人(名称)?/(采购|招标)?代理机构(名称)?:(?P<tenderee>[\w()]{4,25})[,。/]', article_processed)
- if ser2:
- article_processed = article_processed.replace(ser2.group(0), '采购人名称:%s,采购代理机构名称:,' % (
- ser2.group('tenderee')))
- if re.search('中标单位名称:[\w()]{5,25},中标候选人名次:\d,', article_processed) and re.search('中标候选人名次:\d,中标单位名称:[\w()]{5,25},', article_processed)==None: # 处理类似 304706608 此篇的数据源正文特殊表达
- for it in re.finditer('(?P<tenderer>(中标单位名称:[\w()]{5,25},))(?P<rank>(中标候选人名次:\d,))', article_processed):
- article_processed = article_processed.replace(it.group(0), it.group('rank')+it.group('tenderer'))
- ser = re.search('竞得人:\d{8,15}-', article_processed)
- if ser:
- article_processed = article_processed.replace(ser.group(0), '竞得人:') # 修复类似 368120777 关键词角色被编号隔开情况
- article_processed = re.sub("流出方信息:。", "流出方信息:", article_processed) # 修复 367520674 产权批量表格问题
- idx = article_processed.find('供应商报名、缴纳保证金、下载采购文件流程.docx。##attachment##。') # 修复404230599 E交易站源批量附件中标人错误
- if idx > 1000:
- article_processed = article_processed[:idx]
- for it in re.finditer('[一二三四五六七八九十\d]、中标候选人名称,', article_processed): # 修复大纲类标点导致提取不到,例:515521734
- article_processed = re.sub(it.group(0), it.group(0)[:-1]+':', article_processed)
- ser = re.search('项目[编代][码号]/项目名称:(?P<code>(\[审批\])?[\d\-]{10,30})/?(?P<name>[\u4e00-\u9fa5()]{4,35}[,。])', article_processed) # 优化项目编号名称一起写的情况 spxm-53340116.html
- if ser:
- article_processed = article_processed.replace(ser.group(0), '项目代码:%s,项目名称:%s' % (
- ser.group('code'), ser.group('name')))
- article_processed = re.sub('四舍五入至', '', article_processed) # 修复 533537050 ,中标价(四舍五入至万元):6468万元
- if re.search('推荐供应商:', article_processed) and re.search('入围供应商:', article_processed): # 修复 中国工商银行 类网站 入围的才算中标
- article_processed = article_processed.replace('推荐供应商:', '公司名称:')
- if web_source_no.startswith('DX016489') and re.search('排名', article_processed) and re.search('成交供应商单位名称', article_processed): # 20250219 处理特殊站源有排名却叫成交供应商
- article_processed = article_processed.replace('成交供应商单位名称', '成交候选人单位名称')
- '''去除业绩内容'''
- article_processed = del_achievement(article_processed)
- # 修复OCR金额中“,”、“。”识别错误
- article_processed_list = article_processed.split("##attachment##")
- if len(article_processed_list)>1:
- attachment_text = article_processed_list[1]
- for _match in re.finditer("\d。\d{2}",attachment_text):
- _match_text = _match.group()
- attachment_text = attachment_text.replace(_match_text,_match_text.replace("。","."),1)
- # for _match in re.finditer("(\d,\d{3})[,,.]",attachment_text):
- for _match in re.finditer("\d,(?=\d{3}[^\d])",attachment_text):
- _match_text = _match.group()
- attachment_text = attachment_text.replace(_match_text,_match_text.replace(",",","),1)
- article_processed_list[1] = attachment_text
- article_processed = "##attachment##".join(article_processed_list)
- '''特别数据源对 预处理后文本 做特别修改'''
- 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']:
- article_processed = special_treatment(article_processed, web_source_no)
- # 提取bidway
- list_bidway = extract_bidway(article_processed, _title)
- if list_bidway:
- bidway = list_bidway[0].get("body")
- # bidway名称统一规范
- bidway = bidway_integrate(bidway)
- else:
- bidway = ""
- # 修正被","逗号分隔的时间
- repair_time = re.compile("[12]\d,?\d,?\d,?[-—-―/年],?[0-1]?\d,?[-—-―/月],?[0-3]?\d,?[日号]?,?(?:上午|下午)?,?[0-2]?\d,?:,?[0-6]\d,?:,?[0-6]\d|"
- "[12]\d,?\d,?\d,?[-—-―/年],?[0-1]?\d,?[-—-―/月],?[0-3]?\d,?[日号]?,?(?:上午|下午)?,?[0-2]?\d,?[:时点],?[0-6]\d分?|"
- "[12]\d,?\d,?\d,?[-—-―/年],?[0-1]?\d,?[-—-―/月],?[0-3]?\d,?[日号]?,?(?:上午|下午)?,?[0-2]?\d,?[时点]|"
- "[12]\d,?\d,?\d,?[-—-―/年],?[0-1]?\d,?[-—-―/月],?[0-3]?\d,?[日号]|"
- "[0-2]?\d,?:,?[0-6]\d,?:,?[0-6]\d"
- )
- for _time in set(re.findall(repair_time,article_processed)):
- if re.search(",",_time):
- _time2 = re.sub(",", "", _time)
- item = re.search("[12]\d{3}[-—-―/][0-1]?\d[-—-―/][0-3]\d(?=\d)", _time2)
- if item:
- _time2 = _time2.replace(item.group(),item.group() + " ")
- article_processed = article_processed.replace(_time, _time2)
- else:
- item = re.search("[12]\d{3}[-—-―/][0-1]?\d[-—-―/][0-3]\d(?=\d)", _time)
- if item:
- _time2 = _time.replace(item.group(),item.group() + " ")
- article_processed = article_processed.replace(_time, _time2)
- # print('re_rtime',re.findall(repair_time,article_processed))
- # log(article_processed)
- if key_preprocess not in cost_time:
- cost_time[key_preprocess] = 0
- cost_time[key_preprocess] += round(time.time()-start_time,2)
- #article_processed = article[1]
- _article = Article(doc_id,article_processed,sourceContent,_send_doc_id,_title,
- bidway=bidway)
- _article.fingerprint = getFingerprint(_title_raw+sourceContent_raw)
- _article.page_time = page_time
- list_articles.append(_article)
- return list_articles
- def get_preprocessed_sentences(list_articles,useselffool=True,cost_time=dict()):
- '''
- :param list_articles: 经过预处理的article text
- :return: list_sentences
- '''
- list_sentences = []
- list_outlines = []
- for article in list_articles:
- list_sentences_temp = []
- list_entitys_temp = []
- doc_id = article.id
- _send_doc_id = article.doc_id
- _title = article.title
- #表格处理
- key_preprocess = "tableToText"
- start_time = time.time()
- article_processed = article.content
- if len(_title)<100 and _title not in article_processed: # 把标题放到正文
- article_processed = _title + ',' + article_processed # 2023/01/06 标题正文加逗号分割,预防标题后面是产品,正文开头是公司实体,实体识别把产品和公司作为整个角色实体
- attachment_begin_index = -1
- if key_preprocess not in cost_time:
- cost_time[key_preprocess] = 0
- cost_time[key_preprocess] += time.time()-start_time
- #nlp处理
- outline_list = [] # 20240906 修复下面条件不成立时,后面 list_outlines.append(outline_list) 名称未定义报错
- if article_processed is not None and len(article_processed)!=0:
- split_patten = "。"
- sentences = []
- _begin = 0
- sentences_set = set()
- for _iter in re.finditer(split_patten,article_processed):
- _sen = article_processed[_begin:_iter.span()[1]]
- # if len(_sen)>0 and _sen not in sentences_set: # 去重导致内容丢失
- if len(_sen)>0 and (len(sentences)>0 and _sen != sentences[-1] or len(sentences)==0): # 2024/07/25 改为顺序去重
- # 标识在附件里的句子
- if re.search("##attachment##",_sen):
- attachment_begin_index = len(sentences)
- # _sen = re.sub("##attachment##","",_sen)
- sentences.append(_sen)
- sentences_set.add(_sen)
- _begin = _iter.span()[1]
- _sen = article_processed[_begin:]
- if re.search("##attachment##", _sen):
- # _sen = re.sub("##attachment##", "", _sen)
- attachment_begin_index = len(sentences)
- # if len(_sen)>0 and _sen not in sentences_set:
- if len(_sen)>0 and (len(sentences)>0 and _sen != sentences[-1] or len(sentences)==0): # 2024/07/25 改为顺序去重
- sentences.append(_sen)
- sentences_set.add(_sen)
- # 解析outline大纲分段
- outline_list = []
- if re.search("##split##",article.content):
- temp_sentences = []
- last_sentence_index = (-1,-1)
- outline_index = 0
- for sentence_index in range(len(sentences)):
- sentence_text = sentences[sentence_index]
- for _ in re.findall("##split##", sentence_text):
- _match = re.search("##split##", sentence_text)
- if last_sentence_index[0] > -1:
- sentence_begin_index,wordOffset_begin = last_sentence_index
- sentence_end_index = sentence_index
- wordOffset_end = _match.start()
- if sentence_begin_index<attachment_begin_index and sentence_end_index>=attachment_begin_index:
- outline_list.append(Outline(doc_id,outline_index,'',sentence_begin_index,attachment_begin_index-1,wordOffset_begin,len(sentences[attachment_begin_index-1])))
- else:
- outline_list.append(Outline(doc_id,outline_index,'',sentence_begin_index,sentence_end_index,wordOffset_begin,wordOffset_end))
- outline_index += 1
- sentence_text = re.sub("##split##,?", "", sentence_text,count=1)
- last_sentence_index = (sentence_index,_match.start())
- temp_sentences.append(sentence_text)
- if attachment_begin_index>-1 and last_sentence_index[0]<attachment_begin_index:
- 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])))
- else:
- outline_list.append(Outline(doc_id,outline_index,'',last_sentence_index[0],len(sentences)-1,last_sentence_index[1],len(temp_sentences[-1])))
- sentences = temp_sentences
- #解析outline的outline_text内容
- for _outline in outline_list:
- if _outline.sentence_begin_index==_outline.sentence_end_index:
- _text = sentences[_outline.sentence_begin_index][_outline.wordOffset_begin:_outline.wordOffset_end]
- else:
- _text = ""
- for idx in range(_outline.sentence_begin_index,_outline.sentence_end_index+1):
- if idx==_outline.sentence_begin_index:
- _text += sentences[idx][_outline.wordOffset_begin:]
- elif idx==_outline.sentence_end_index:
- _text += sentences[idx][:_outline.wordOffset_end]
- else:
- _text += sentences[idx]
- _outline.outline_text = _text
- _outline_summary = re.split("[::,]",_text,1)[0]
- if len(_outline_summary)<30:
- _outline.outline_summary = _outline_summary
- # print(_outline.outline_index,_outline.outline_text)
- article.content = "".join(sentences)
- # sentences.append(article_processed[_begin:])
- article.content = re.sub('[,。\s]+。', '。', article.content) # 处理连续标点
- lemmas = []
- doc_offsets = []
- dep_types = []
- dep_tokens = []
- time1 = time.time()
- '''
- tokens_all = fool.cut(sentences)
- #pos_all = fool.LEXICAL_ANALYSER.pos(tokens_all)
- #ner_tag_all = fool.LEXICAL_ANALYSER.ner_labels(sentences,tokens_all)
- ner_entitys_all = fool.ner(sentences)
- '''
- #限流执行
- key_nerToken = "nerToken"
- start_time = time.time()
- # tokens_all = getTokens(sentences,useselffool=useselffool)
- tokens_all = getTokens([re.sub("##attachment_begin##|##attachment_end##","",_sen) for _sen in sentences],useselffool=useselffool)
- if key_nerToken not in cost_time:
- cost_time[key_nerToken] = 0
- cost_time[key_nerToken] += round(time.time()-start_time,2)
- in_attachment = False
- for sentence_index in range(len(sentences)):
- sentence_text = sentences[sentence_index]
- if re.search("##attachment_begin##",sentence_text):
- in_attachment = True
- sentence_text = re.sub("##attachment_begin##","",sentence_text)
- if re.search("##attachment_end##",sentence_text):
- in_attachment = False
- sentence_text = re.sub("##attachment_end##", "", sentence_text)
- if sentence_index >= attachment_begin_index and attachment_begin_index!=-1:
- in_attachment = True
- tokens = tokens_all[sentence_index]
- #pos_tag = pos_all[sentence_index]
- pos_tag = ""
- ner_entitys = ""
- 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))
- if len(list_sentences_temp)==0:
- list_sentences_temp.append(Sentences(doc_id=doc_id,sentence_index=0,sentence_text="sentence_text",tokens=[],pos_tags=[],ner_tags=""))
- list_sentences.append(list_sentences_temp)
- list_outlines.append(outline_list)
- article.content = re.sub("##attachment_begin##|##attachment_end##", "", article.content)
- return list_sentences,list_outlines
- def cut_repeat_name(s):
- '''
- 公司连续重复名称去重
- :param s:
- :return:
- '''
- if len(s) >= 8:
- n = s.count(s[-4:])
- id = s.find(s[-4:]) + 4
- sub_s = s[:id]
- if n>=2 and s == sub_s * n:
- s = sub_s
- return s
- def get_preprocessed_entitys(list_sentences,useselffool=True,cost_time=dict()):
- '''
- :param list_sentences:分局情况
- :param cost_time:
- :return: list_entitys
- '''
- list_entitys = []
- not_extract_roles = ['黄埔军校', '国有资产管理处', '五金建材', '铝合金门窗', '华电XX发电有限公司', '华电XXX发电有限公司', '中标(成交)公司', '贵州茅台', '贵州茅台酒', '陕西省省级国'] # 需要过滤掉的企业单位
- for list_sentence in list_sentences:
- sentences = []
- list_entitys_temp = []
- for _sentence in list_sentence:
- sentences.append(_sentence.sentence_text)
- time1 = time.time()
- '''
- tokens_all = fool.cut(sentences)
- #pos_all = fool.LEXICAL_ANALYSER.pos(tokens_all)
- #ner_tag_all = fool.LEXICAL_ANALYSER.ner_labels(sentences,tokens_all)
- ner_entitys_all = fool.ner(sentences)
- '''
- #限流执行
- key_nerToken = "nerToken"
- start_time = time.time()
- found_yeji = 0 # 2021/8/6 增加判断是否正文包含评标结果 及类似业绩判断用于过滤后面的金额
- # found_pingbiao = False
- ner_entitys_all = getNers(sentences,useselffool=useselffool)
- if key_nerToken not in cost_time:
- cost_time[key_nerToken] = 0
- cost_time[key_nerToken] += round(time.time()-start_time,2)
- doctextcon_sentence_len = sum([1 for sentence in list_sentence if not sentence.in_attachment])
- company_dict = set()
- company_index = dict((i,set()) for i in range(len(list_sentence)))
- for sentence_index in range(len(list_sentence)):
- list_sentence_entitys = []
- sentence_text = list_sentence[sentence_index].sentence_text
- tokens = list_sentence[sentence_index].tokens
- doc_id = list_sentence[sentence_index].doc_id
- in_attachment = list_sentence[sentence_index].in_attachment
- list_tokenbegin = []
- begin = 0
- for i in range(0,len(tokens)):
- list_tokenbegin.append(begin)
- begin += len(str(tokens[i]))
- list_tokenbegin.append(begin+1)
- #pos_tag = pos_all[sentence_index]
- pos_tag = ""
- ner_entitys = ner_entitys_all[sentence_index]
- '''正则识别角色实体 经营部|经销部|电脑部|服务部|复印部|印刷部|彩印部|装饰部|修理部|汽修部|修理店|零售店|设计店|服务店|家具店|专卖店|分店|文具行|商行|印刷厂|修理厂|维修中心|修配中心|养护中心|服务中心|会馆|文化馆|超市|门市|商场|家具城|印刷社|经销处'''
- for it in re.finditer(
- '(?P<text_key_word>(((单一来源|中标|中选|中价|成交)(供应商|供货商|服务商|候选人|单位|人))|(供应商|供货商|服务商|候选人))(名称)?[为::]+)(?P<text>([()\w]{5,20})(厂|中心|超市|门市|商场|工作室|文印室|城|部|店|站|馆|行|社|处))[,。]',
- sentence_text):
- for k, v in it.groupdict().items():
- if k == 'text_key_word':
- keyword = v
- if k == 'text':
- entity = v
- b = it.start() + len(keyword)
- e = it.end() - 1
- if (b, e, 'location', entity) in ner_entitys:
- ner_entitys.remove((b, e, 'location', entity))
- ner_entitys.append((b, e, 'company', entity))
- elif (b, e, 'org', entity) not in ner_entitys and (b, e, 'company', entity) not in ner_entitys:
- ner_entitys.append((b, e, 'company', entity))
- for it in re.finditer(
- '(?P<text_key_word>((建设|招租|招标|采购)(单位|人)|业主)(名称)?[为::]+)(?P<text>\w{2,4}[省市县区镇]([()\w]{2,20})(管理处|办公室|委员会|村委会|纪念馆|监狱|管教所|修养所|社区|农场|林场|羊场|猪场|石场|村|幼儿园|海关|殡仪馆)|海门\w{2,15}村)[,。]',
- sentence_text):
- for k, v in it.groupdict().items():
- if k == 'text_key_word':
- keyword = v
- if k == 'text':
- entity = v
- b = it.start() + len(keyword)
- e = it.end() - 1
- if (b, e, 'location', entity) in ner_entitys:
- ner_entitys.remove((b, e, 'location', entity))
- ner_entitys.append((b, e, 'org', entity))
- if (b, e, 'org', entity) not in ner_entitys and (b, e, 'company', entity) not in ner_entitys:
- ner_entitys.append((b, e, 'org', entity))
- for ner_entity in ner_entitys:
- if ner_entity[2] in ['company','org']:
- company_dict.add((ner_entity[2],ner_entity[3]))
- company_index[sentence_index].add((ner_entity[0],ner_entity[1]))
- #识别package
- ner_time_list = []
- #识别实体
- for ner_entity in ner_entitys:
- begin_index_temp = ner_entity[0]
- end_index_temp = ner_entity[1]
- entity_type = ner_entity[2]
- entity_text = ner_entity[3]
- if entity_type in ["org", "company"] and re.search('^((特殊)?普通合伙)|^(有限合伙)', sentence_text[end_index_temp:]): # 规则补充合伙关键词
- partnership = re.search('^((特殊)?普通合伙)', sentence_text[end_index_temp:]).group(0)
- end_index_temp += len(partnership)
- entity_text += partnership
- if entity_type == 'location' and re.search('^\w{2,4}[市县]\w{2,15}(中心|监狱|殡仪馆|水利站)$', entity_text) and \
- re.search('\d[楼层号]', entity_text)==None: # 2024/06/07 修改错误地址实体为角色
- entity_type = 'org'
- if begin_index_temp>0 and '县' in entity_text and re.match('前郭尔罗斯蒙古族自治县|积石山县', sentence_text[begin_index_temp-1:end_index_temp]): #20240905 修复实体识别少字问题
- entity_text = sentence_text[begin_index_temp-1] + entity_text
- begin_index_temp -= 1
- ner_entity = (begin_index_temp, end_index_temp, entity_type, entity_text)
- elif entity_text == '中华人民共和国' and re.search('^\w{2,4}海关', sentence_text[end_index_temp: end_index_temp+6]): # 2024/04/24 修复 采购单位:中华人民共和国汕尾海关, 识别不到海关
- ser = re.search('^\w{2,4}海关', sentence_text[end_index_temp: end_index_temp+6])
- entity_text += ser.group(0)
- end_index_temp += ser.end()
- ner_entity = (begin_index_temp, end_index_temp, entity_type, entity_text)
- if entity_type=='time':
- ner_time_list.append((begin_index_temp,end_index_temp))
- if entity_type in ["org","company"] and not isLegalEnterprise(entity_text):
- continue
- # 实体长度限制
- if entity_type in ["org","company"] and len(entity_text)>30:
- continue
- if entity_type == "person" and len(entity_text) > 20:
- continue
- elif entity_type=="person" and len(entity_text)>10 and len(re.findall("[\u4e00-\u9fa5]",entity_text))<len(entity_text)/2:
- continue
- # 识别不完整的组织机构补充
- # if entity_type in ["org"]:
- # end_words = re.search("^[\u4e00-\u9fa5]{,5}(?:办公室|部|中心|处|会)",sentence_text[end_index_temp:end_index_temp+10]) # 2024/4/7 注释掉 273356356 江门市新会区大鳌镇农村集体资产资源交易中心受新会
- # if end_words:
- # entity_text = entity_text + end_words.group()
- for j in range(len(list_tokenbegin)):
- if list_tokenbegin[j]==begin_index_temp:
- begin_index = j
- break
- elif list_tokenbegin[j]>begin_index_temp:
- begin_index = j-1
- break
- begin_index_temp += len(str(entity_text))
- for j in range(begin_index,len(list_tokenbegin)):
- if list_tokenbegin[j]>=begin_index_temp:
- end_index = j-1
- break
- entity_id = "%s_%d_%d_%d"%(doc_id,sentence_index,begin_index,end_index)
- #去掉标点符号
- if entity_type!='time':
- entity_text = re.sub("[,,。:!&@$\*\s;;]","",entity_text) # 215553737
- entity_text = entity_text.replace("(","(").replace(")",")") if isinstance(entity_text,str) else entity_text
- # 组织机构实体名称补充
- if entity_type in ["org", "company"]:
- if entity_text in not_extract_roles: # 过滤掉名称在 需要过滤企业单位列表里的
- continue
- if not re.search("有限责任公司|有限公司",entity_text):
- fix_name = re.search("(有限)([责贵]?任?)(公?司?)",entity_text)
- if fix_name:
- if len(fix_name.group(2))>0:
- _text = fix_name.group()
- if '司' in _text:
- entity_text = entity_text.replace(_text, "有限责任公司")
- else:
- _text = re.search(_text + "[^司]{0,5}司", entity_text)
- if _text:
- _text = _text.group()
- entity_text = entity_text.replace(_text, "有限责任公司")
- else:
- entity_text = entity_text.replace(entity_text[fix_name.start():], "有限责任公司")
- elif len(fix_name.group(3))>0:
- _text = fix_name.group()
- if '司' in _text:
- entity_text = entity_text.replace(_text, "有限公司")
- else:
- _text = re.search(_text + "[^司]{0,3}司", entity_text)
- if _text:
- _text = _text.group()
- entity_text = entity_text.replace(_text, "有限公司")
- else:
- entity_text = entity_text.replace(entity_text[fix_name.start():], "有限公司")
- elif re.search("有限$", entity_text):
- entity_text = re.sub("有限$","有限公司",entity_text)
- entity_text = entity_text.replace("有公司","有限公司")
- '''下面对公司实体进行清洗'''
- entity_text = re.sub('\s', '', entity_text)
- if re.search('^(\d{4}年)?[\-\d月日份]*\w{2,3}分公司$|^\w{,6}某(部|医院)$', entity_text): # 删除
- # print('公司实体不符合规范:', entity_text)
- continue
- elif re.match('xx|XX', entity_text): # 删除
- # print('公司实体不符合规范:', entity_text)
- continue
- elif re.match('\.?(rar|zip|pdf|df|doc|docx|xls|xlsx|jpg|png)', entity_text):
- entity_text = re.sub('\.?(rar|zip|pdf|df|doc|docx|xls|xlsx|jpg|png)', '', entity_text)
- elif re.match(
- '((\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]+',
- entity_text):
- filter = re.match(
- '((\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]+',
- entity_text).group(1)
- entity_text = entity_text.replace(filter, '')
- elif re.search('\]|\[|\]|[【】{}「?:∶〔·.\'#~_ΓΙεⅠ]', entity_text):
- entity_text = re.sub('\]|\[|\]|[【】「?:∶〔·.\'#~_ΓΙεⅠ]', '', entity_text)
- if len(re.sub('(项目|分|有限)?公司|集团|制造部|中心|医院|学校|大学|中学|小学|幼儿园', '', entity_text))<2:
- # print('公司实体不符合规范:', entity_text)
- continue
- entity_text = cut_repeat_name(entity_text) # 20231201 重复名称去重 如:中山大学附属第一医院中山大学附属第一医院中山大学附属第一医院
- 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))
- # 标记文章末尾的"发布人”、“发布时间”实体
- if sentence_index==len(list_sentence)-1 or sentence_index==doctextcon_sentence_len-1:
- if len(list_sentence_entitys[-2:])==2:
- second2last = list_sentence_entitys[-2]
- last = list_sentence_entitys[-1]
- if (second2last.entity_type in ["company",'org'] and last.entity_type=="time") or (
- second2last.entity_type=="time" and last.entity_type in ["company",'org']):
- if last.wordOffset_begin - second2last.wordOffset_end < 6 and len(sentence_text) - last.wordOffset_end<6:
- last.is_tail = True
- second2last.is_tail = True
- #使用正则识别金额
- money_list, found_yeji = get_money_entity(sentence_text, found_yeji, in_attachment)
- entity_type = "money"
- for money in money_list:
- # print('money: ', money)
- entity_text, begin_index, end_index, unit, notes = money
- end_index = end_index - 1 if entity_text.endswith(',') else end_index
- entity_id = "%s_%d_%d_%d" % (doc_id, sentence_index, begin_index, end_index)
- _exists = False
- for item in list_sentence_entitys:
- if item.entity_id==entity_id and item.entity_type==entity_type:
- _exists = True
- if (begin_index >=item.wordOffset_begin and begin_index<item.wordOffset_end) or (end_index>item.wordOffset_begin and end_index<=item.wordOffset_end):
- _exists = True
- # print('_exists: ',begin_index, end_index, item.wordOffset_begin, item.wordOffset_end, item.entity_text, item.entity_type)
- if not _exists:
- if float(entity_text)>1:
- # if symbol == '-': # 负值金额保留负号
- # entity_text = '-'+entity_text # 20230414 取消符号
- begin_words = changeIndexFromWordToWords(tokens, begin_index)
- end_words = changeIndexFromWordToWords(tokens, end_index)
- # print('金额位置: ', begin_index, begin_words,end_index, end_words)
- # print('金额召回: ', entity_text, sentence_text[begin_index:end_index], tokens[begin_words:end_words])
- 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))
- list_sentence_entitys[-1].notes = notes # 2021/7/20 新增金额备注
- list_sentence_entitys[-1].money_unit = unit # 2021/7/20 新增金额备注
- # print('预处理中的 金额:%s, 单位:%s'%(entity_text,unit))
- # print(entity_text,unit,notes)
- # "联系人"正则补充提取 2021/11/15 新增
- list_person_text = [entity.entity_text for entity in list_sentence_entitys if entity.entity_type=='person']
- error_text = ['交易','机构','教育','项目','公司','中标','开标','截标','监督','政府','国家','中国','技术','投标','传真','网址','电子邮',
- '联系','联系电','联系地','采购代','邮政编','邮政','电话','手机','手机号','联系人','地址','地点','邮箱','邮编','联系方','招标','招标人','代理',
- '代理人','采购','附件','注意','登录','报名','踏勘',"测试",'交货']
- list_person_text = set(list_person_text + error_text)
- re_person = re.compile("联系人[::]([\u4e00-\u9fa5]工)|"
- "联系人[::]([\u4e00-\u9fa5]{2,3})(?=,?联系)|"
- "联系人[::]([\u4e00-\u9fa5]{2,3})(?=[,。;、])"
- )
- list_person = []
- if not in_attachment:
- for match_result in re_person.finditer(sentence_text):
- match_text = match_result.group()
- entity_text = match_text[4:]
- wordOffset_begin = match_result.start() + 4
- wordOffset_end = match_result.end()
- # print(text[wordOffset_begin:wordOffset_end])
- # 排除一些不为人名的实体
- if re.search("^[\u4e00-\u9fa5]{7,}([,。]|$)",sentence_text[wordOffset_begin:wordOffset_begin+20]):
- continue
- if entity_text not in list_person_text and entity_text[:2] not in list_person_text:
- _person = dict()
- _person['body'] = entity_text
- _person['begin_index'] = wordOffset_begin
- _person['end_index'] = wordOffset_end
- list_person.append(_person)
- entity_type = "person"
- for person in list_person:
- begin_index_temp = person['begin_index']
- for j in range(len(list_tokenbegin)):
- if list_tokenbegin[j] == begin_index_temp:
- begin_index = j
- break
- elif list_tokenbegin[j] > begin_index_temp:
- begin_index = j - 1
- break
- index = person['end_index']
- end_index_temp = index
- for j in range(begin_index, len(list_tokenbegin)):
- if list_tokenbegin[j] >= index:
- end_index = j - 1
- break
- entity_id = "%s_%d_%d_%d" % (doc_id, sentence_index, begin_index, end_index)
- entity_text = person['body']
- 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,in_attachment=in_attachment))
- # 时间实体格式补充
- 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])")
- entity_type = "time"
- for _time in re.finditer(re_time_new,sentence_text):
- entity_text = _time.group()
- begin_index_temp = _time.start()
- end_index_temp = _time.end()
- is_same = False
- for t_index in ner_time_list:
- if begin_index_temp>=t_index[0] and end_index_temp<=t_index[1]:
- is_same = True
- break
- if is_same:
- continue
- if _time.start()!=0 and re.search("\d",sentence_text[_time.start()-1:_time.start()]):
- continue
- # 纯数字格式,例:20190509
- if re.search("^\d{8}$",entity_text):
- if _time.end()!=len(sentence_text) and re.search("[\da-zA-z]",sentence_text[_time.end():_time.end()+1]):
- continue
- entity_text = entity_text[:4] + "-" + entity_text[4:6] + "-" + entity_text[6:8]
- if not timeFormat(entity_text):
- continue
- for j in range(len(list_tokenbegin)):
- if list_tokenbegin[j] == begin_index_temp:
- begin_index = j
- break
- elif list_tokenbegin[j] > begin_index_temp:
- begin_index = j - 1
- break
- for j in range(begin_index, len(list_tokenbegin)):
- if list_tokenbegin[j] >= end_index_temp:
- end_index = j - 1
- break
- entity_id = "%s_%d_%d_%d" % (doc_id, sentence_index, begin_index, end_index)
- 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, in_attachment=in_attachment))
- # 资金来源提取 2020/12/30 新增
- list_moneySource = extract_moneySource(sentence_text)
- entity_type = "moneysource"
- for moneySource in list_moneySource:
- entity_text = moneySource['body']
- if len(entity_text)>50:
- continue
- begin_index_temp = moneySource['begin_index']
- for j in range(len(list_tokenbegin)):
- if list_tokenbegin[j] == begin_index_temp:
- begin_index = j
- break
- elif list_tokenbegin[j] > begin_index_temp:
- begin_index = j - 1
- break
- index = moneySource['end_index']
- end_index_temp = index
- for j in range(begin_index, len(list_tokenbegin)):
- if list_tokenbegin[j] >= index:
- end_index = j - 1
- break
- entity_id = "%s_%d_%d_%d" % (doc_id, sentence_index, begin_index, end_index)
- 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,in_attachment=in_attachment,prob=moneySource['prob']))
- # 电子邮箱提取 2021/11/04 新增
- list_email = extract_email(sentence_text)
- entity_type = "email" # 电子邮箱
- for email in list_email:
- begin_index_temp = email['begin_index']
- for j in range(len(list_tokenbegin)):
- if list_tokenbegin[j] == begin_index_temp:
- begin_index = j
- break
- elif list_tokenbegin[j] > begin_index_temp:
- begin_index = j - 1
- break
- index = email['end_index']
- end_index_temp = index
- for j in range(begin_index, len(list_tokenbegin)):
- if list_tokenbegin[j] >= index:
- end_index = j - 1
- break
- entity_id = "%s_%d_%d_%d" % (doc_id, sentence_index, begin_index, end_index)
- entity_text = email['body']
- 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,in_attachment=in_attachment))
- # 服务期限提取 2020/12/30 新增
- list_servicetime = extract_servicetime(sentence_text)
- entity_type = "serviceTime"
- for servicetime in list_servicetime:
- entity_text = servicetime['body']
- begin_index_temp = servicetime['begin_index']
- for j in range(len(list_tokenbegin)):
- if list_tokenbegin[j] == begin_index_temp:
- begin_index = j
- break
- elif list_tokenbegin[j] > begin_index_temp:
- begin_index = j - 1
- break
- index = servicetime['end_index']
- end_index_temp = index
- for j in range(begin_index, len(list_tokenbegin)):
- if list_tokenbegin[j] >= index:
- end_index = j - 1
- break
- entity_id = "%s_%d_%d_%d" % (doc_id, sentence_index, begin_index, end_index)
- 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,in_attachment=in_attachment, prob=servicetime["prob"]))
- # 2021/12/29 新增比率提取
- list_ratio = extract_ratio(sentence_text)
- entity_type = "ratio"
- for ratio in list_ratio:
- # print("ratio", ratio)
- begin_index_temp = ratio['begin_index']
- for j in range(len(list_tokenbegin)):
- if list_tokenbegin[j] == begin_index_temp:
- begin_index = j
- break
- elif list_tokenbegin[j] > begin_index_temp:
- begin_index = j - 1
- break
- index = ratio['end_index']
- end_index_temp = index
- for j in range(begin_index, len(list_tokenbegin)):
- if list_tokenbegin[j] >= index:
- end_index = j - 1
- break
- entity_id = "%s_%d_%d_%d" % (doc_id, sentence_index, begin_index, end_index)
- entity_text = ratio['body']
- ratio_value = (ratio['value'],ratio['type'])
- _entity = Entity(doc_id, entity_id, entity_text, entity_type, sentence_index, begin_index, end_index,
- begin_index_temp, end_index_temp,in_attachment=in_attachment)
- _entity.ratio_value = ratio_value
- list_sentence_entitys.append(_entity)
- list_sentence_entitys.sort(key=lambda x:x.begin_index)
- list_entitys_temp = list_entitys_temp+list_sentence_entitys
- # 补充ner模型未识别全的company/org实体
- for sentence_index in range(len(list_sentence)):
- sentence_text = list_sentence[sentence_index].sentence_text
- tokens = list_sentence[sentence_index].tokens
- doc_id = list_sentence[sentence_index].doc_id
- in_attachment = list_sentence[sentence_index].in_attachment
- list_tokenbegin = []
- begin = 0
- for i in range(0, len(tokens)):
- list_tokenbegin.append(begin)
- begin += len(str(tokens[i]))
- list_tokenbegin.append(begin + 1)
- add_sentence_entitys = []
- company_dict = sorted(list(company_dict),key=lambda x:len(x[1]),reverse=True)
- for company_type,company_text in company_dict:
- begin_index_list = findAllIndex(company_text,sentence_text)
- for begin_index in begin_index_list:
- is_continue = False
- for t_begin,t_end in list(company_index[sentence_index]):
- if begin_index>=t_begin and begin_index+len(company_text)<=t_end:
- is_continue = True
- break
- if not is_continue:
- add_sentence_entitys.append((begin_index,begin_index+len(company_text),company_type,company_text))
- company_index[sentence_index].add((begin_index,begin_index+len(company_text)))
- else:
- continue
- for ner_entity in add_sentence_entitys:
- begin_index_temp = ner_entity[0]
- end_index_temp = ner_entity[1]
- entity_type = ner_entity[2]
- entity_text = ner_entity[3]
- if entity_type in ["org","company"] and not isLegalEnterprise(entity_text):
- continue
- for j in range(len(list_tokenbegin)):
- if list_tokenbegin[j]==begin_index_temp:
- begin_index = j
- break
- elif list_tokenbegin[j]>begin_index_temp:
- begin_index = j-1
- break
- begin_index_temp += len(str(entity_text))
- for j in range(begin_index,len(list_tokenbegin)):
- if list_tokenbegin[j]>=begin_index_temp:
- end_index = j-1
- break
- entity_id = "%s_%d_%d_%d"%(doc_id,sentence_index,begin_index,end_index)
- if entity_type in ["org","company"] and entity_text in not_extract_roles: # 过滤掉名称在 需要过滤企业单位列表里的
- continue
- #去掉标点符号
- entity_text = re.sub("[,,。:!&@$\*]","",entity_text)
- entity_text = entity_text.replace("(","(").replace(")",")") if isinstance(entity_text,str) else entity_text
- 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))
- list_entitys_temp.sort(key=lambda x:(x.sentence_index,x.begin_index))
- list_entitys.append(list_entitys_temp)
- return list_entitys
-
- def union_result(codeName,prem):
- '''
- @summary:模型的结果拼成字典
- @param:
- codeName:编号名称模型的结果字典
- prem:拿到属性的角色的字典
- @return:拼接起来的字典
- '''
- result = []
- assert len(codeName)==len(prem)
- for item_code,item_prem in zip(codeName,prem):
- result.append(dict(item_code,**item_prem))
- return result
- def persistenceData(data):
- '''
- @summary:将中间结果保存到数据库-线上生产的时候不需要执行
- '''
- import psycopg2
- conn = psycopg2.connect(dbname="BiddingKG",user="postgres",password="postgres",host="192.168.2.101")
- cursor = conn.cursor()
- for item_index in range(len(data)):
- item = data[item_index]
- doc_id = item[0]
- dic = item[1]
- code = dic['code']
- name = dic['name']
- prem = dic['prem']
- if len(code)==0:
- code_insert = ""
- else:
- code_insert = ";".join(code)
- prem_insert = ""
- for item in prem:
- for x in item:
- if isinstance(x, list):
- if len(x)>0:
- for x1 in x:
- prem_insert+="/".join(x1)+","
- prem_insert+="$"
- else:
- prem_insert+=str(x)+"$"
- prem_insert+=";"
- sql = " insert into predict_validation(doc_id,code,name,prem) values('"+doc_id+"','"+code_insert+"','"+name+"','"+prem_insert+"')"
- cursor.execute(sql)
- conn.commit()
- conn.close()
-
- def persistenceData1(list_entitys,list_sentences):
- '''
- @summary:将中间结果保存到数据库-线上生产的时候不需要执行
- '''
- import psycopg2
- conn = psycopg2.connect(dbname="BiddingKG",user="postgres",password="postgres",host="192.168.2.101")
- cursor = conn.cursor()
- for list_entity in list_entitys:
- for entity in list_entity:
- if entity.values is not None:
- 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)+")"
- else:
- 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)+")"
- cursor.execute(sql)
- for list_sentence in list_sentences:
- for sentence in list_sentence:
- str_tokens = "["
- for item in sentence.tokens:
- str_tokens += "'"
- if item=="'":
- str_tokens += "''"
- else:
- str_tokens += item
- str_tokens += "',"
- str_tokens = str_tokens[:-1]+"]"
- sql = " insert into predict_sentences(doc_id,sentence_index,tokens) values('"+sentence.doc_id+"',"+str(sentence.sentence_index)+",array"+str_tokens+")"
- cursor.execute(sql)
- conn.commit()
- conn.close()
- def _handle(item,result_queue):
- dochtml = item["dochtml"]
- docid = item["docid"]
- list_innerTable = tableToText(BeautifulSoup(dochtml,"lxml"))
- flag = False
- if list_innerTable:
- flag = True
- for table in list_innerTable:
- result_queue.put({"docid":docid,"json_table":json.dumps(table,ensure_ascii=False)})
- def getPredictTable():
- filename = "D:\Workspace2016\DataExport\data\websouce_doc.csv"
- import pandas as pd
- import json
- from BiddingKG.dl.common.MultiHandler import MultiHandler,Queue
- df = pd.read_csv(filename)
- df_data = {"json_table":[],"docid":[]}
- _count = 0
- _sum = len(df["docid"])
- task_queue = Queue()
- result_queue = Queue()
- _index = 0
- for dochtml,docid in zip(df["dochtmlcon"],df["docid"]):
- task_queue.put({"docid":docid,"dochtml":dochtml,"json_table":None})
- _index += 1
- mh = MultiHandler(task_queue=task_queue,task_handler=_handle,result_queue=result_queue,process_count=5,thread_count=1)
- mh.run()
- while True:
- try:
- item = result_queue.get(block=True,timeout=1)
- df_data["docid"].append(item["docid"])
- df_data["json_table"].append(item["json_table"])
- except Exception as e:
- print(e)
- break
- df_1 = pd.DataFrame(df_data)
- df_1.to_csv("../form/websource_67000_table.csv",columns=["docid","json_table"])
- if __name__=="__main__":
- '''
- import glob
- for file in glob.glob("C:\\Users\\User\\Desktop\\test\\*.html"):
- file_txt = str(file).replace("html","txt")
- with codecs.open(file_txt,"a+",encoding="utf8") as f:
- f.write("\n================\n")
- content = codecs.open(file,"r",encoding="utf8").read()
- f.write(segment(tableToText(BeautifulSoup(content,"lxml"))))
- '''
- # content = codecs.open("C:\\Users\\User\\Desktop\\2.html","r",encoding="utf8").read()
- # print(segment(tableToText(BeautifulSoup(content,"lxml"))))
- # getPredictTable()
- text = '是否拟中标人:是,评标排名:1,价格类型:(万元)报价:13311.1582,得分:84.46,项目负责人:邓焱文'
- text = ',采购包1:采购包预算金额(元:1,500000.00,采购包最高限价(元:1,430600.00,'
- text = '成交人:中坤电力有限公司,成交价格:11493,603.52元,质量:合格,项目工期:117天,'
- text = '3年投标报价(元)含税 6299700.00'
- # text = '数量及单位1:65台,单价2:800,投标报价3=1×2:52000。'
- print(get_money_entity(text, found_yeji=0))
- # with open('D:/138786703.html', 'r', encoding='utf-8') as f:
- # sourceContent = f.read()
- # # article_processed = segment(tableToText(BeautifulSoup(sourceContent, "lxml")))
- # # print(article_processed)
- #
- # list_articles, list_sentences, list_entitys, _cost_time = get_preprocessed([['doc_id', sourceContent, "", "", '', '2021-02-01']], useselffool=True)
- # for entity in list_entitys[0]:
- # print(entity.entity_type, entity.entity_text)
|