Preprocessing.py 173 KB

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