Preprocessing.py 220 KB

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