Preprocessing.py 192 KB

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