Preprocessing.py 204 KB

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