Preprocessing.py 212 KB

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