Preprocessing.py 143 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902
  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
  16. from BiddingKG.dl.common.nerUtils import *
  17. from BiddingKG.dl.money.moneySource.ruleExtra import extract_moneySource
  18. from BiddingKG.dl.time.re_servicetime import extract_servicetime
  19. from BiddingKG.dl.relation_extraction.re_email import extract_email
  20. from BiddingKG.dl.bidway.re_bidway import extract_bidway,bidway_integrate
  21. from BiddingKG.dl.fingerprint.documentFingerprint import getFingerprint
  22. from BiddingKG.dl.entityLink.entityLink import *
  23. #
  24. def tableToText(soup):
  25. '''
  26. @param:
  27. soup:网页html的soup
  28. @return:处理完表格信息的网页text
  29. '''
  30. def getTrs(tbody):
  31. #获取所有的tr
  32. trs = []
  33. objs = tbody.find_all(recursive=False)
  34. for obj in objs:
  35. if obj.name=="tr":
  36. trs.append(obj)
  37. if obj.name=="tbody":
  38. for tr in obj.find_all("tr",recursive=False):
  39. trs.append(tr)
  40. return trs
  41. def fixSpan(tbody):
  42. # 处理colspan, rowspan信息补全问题
  43. #trs = tbody.findChildren('tr', recursive=False)
  44. trs = getTrs(tbody)
  45. ths_len = 0
  46. ths = list()
  47. trs_set = set()
  48. #修改为先进行列补全再进行行补全,否则可能会出现表格解析混乱
  49. # 遍历每一个tr
  50. for indtr, tr in enumerate(trs):
  51. ths_tmp = tr.findChildren('th', recursive=False)
  52. #不补全含有表格的tr
  53. if len(tr.findChildren('table'))>0:
  54. continue
  55. if len(ths_tmp) > 0:
  56. ths_len = ths_len + len(ths_tmp)
  57. for th in ths_tmp:
  58. ths.append(th)
  59. trs_set.add(tr)
  60. # 遍历每行中的element
  61. tds = tr.findChildren(recursive=False)
  62. for indtd, td in enumerate(tds):
  63. # 若有colspan 则补全同一行下一个位置
  64. if 'colspan' in td.attrs:
  65. if str(re.sub("[^0-9]","",str(td['colspan'])))!="":
  66. col = int(re.sub("[^0-9]","",str(td['colspan'])))
  67. if col<100 and len(td.get_text())<1000:
  68. td['colspan'] = 1
  69. for i in range(1, col, 1):
  70. td.insert_after(copy.copy(td))
  71. for indtr, tr in enumerate(trs):
  72. ths_tmp = tr.findChildren('th', recursive=False)
  73. #不补全含有表格的tr
  74. if len(tr.findChildren('table'))>0:
  75. continue
  76. if len(ths_tmp) > 0:
  77. ths_len = ths_len + len(ths_tmp)
  78. for th in ths_tmp:
  79. ths.append(th)
  80. trs_set.add(tr)
  81. # 遍历每行中的element
  82. tds = tr.findChildren(recursive=False)
  83. for indtd, td in enumerate(tds):
  84. # 若有rowspan 则补全下一行同样位置
  85. if 'rowspan' in td.attrs:
  86. if str(re.sub("[^0-9]","",str(td['rowspan'])))!="":
  87. row = int(re.sub("[^0-9]","",str(td['rowspan'])))
  88. td['rowspan'] = 1
  89. for i in range(1, row, 1):
  90. # 获取下一行的所有td, 在对应的位置插入
  91. if indtr+i<len(trs):
  92. tds1 = trs[indtr + i].findChildren(['td','th'], recursive=False)
  93. if len(tds1) >= (indtd) and len(tds1)>0:
  94. if indtd > 0:
  95. tds1[indtd - 1].insert_after(copy.copy(td))
  96. else:
  97. tds1[0].insert_before(copy.copy(td))
  98. elif indtd-2>0 and len(tds1) > 0 and len(tds1) == indtd - 1: # 修正某些表格最后一列没补全
  99. tds1[indtd-2].insert_after(copy.copy(td))
  100. def getTable(tbody):
  101. #trs = tbody.findChildren('tr', recursive=False)
  102. trs = getTrs(tbody)
  103. inner_table = []
  104. for tr in trs:
  105. tr_line = []
  106. tds = tr.findChildren(['td','th'], recursive=False)
  107. if len(tds)==0:
  108. tr_line.append([re.sub('\xa0','',segment(tr,final=False)),0]) # 2021/12/21 修复部分表格没有td 造成数据丢失
  109. for td in tds:
  110. tr_line.append([re.sub('\xa0','',segment(td,final=False)),0])
  111. #tr_line.append([td.get_text(),0])
  112. inner_table.append(tr_line)
  113. return inner_table
  114. #处理表格不对齐的问题
  115. def fixTable(inner_table,fix_value="~~"):
  116. maxWidth = 0
  117. for item in inner_table:
  118. if len(item)>maxWidth:
  119. maxWidth = len(item)
  120. for i in range(len(inner_table)):
  121. if len(inner_table[i])<maxWidth:
  122. for j in range(maxWidth-len(inner_table[i])):
  123. inner_table[i].append([fix_value,0])
  124. return inner_table
  125. def removePadding(inner_table,pad_row = "@@",pad_col = "##"):
  126. height = len(inner_table)
  127. width = len(inner_table[0])
  128. for i in range(height):
  129. point = ""
  130. for j in range(width):
  131. if inner_table[i][j][0]==point and point!="":
  132. inner_table[i][j][0] = pad_row
  133. else:
  134. if inner_table[i][j][0] not in [pad_row,pad_col]:
  135. point = inner_table[i][j][0]
  136. for j in range(width):
  137. point = ""
  138. for i in range(height):
  139. if inner_table[i][j][0]==point and point!="":
  140. inner_table[i][j][0] = pad_col
  141. else:
  142. if inner_table[i][j][0] not in [pad_row,pad_col]:
  143. point = inner_table[i][j][0]
  144. def addPadding(inner_table,pad_row = "@@",pad_col = "##"):
  145. height = len(inner_table)
  146. width = len(inner_table[0])
  147. for i in range(height):
  148. for j in range(width):
  149. if inner_table[i][j][0]==pad_row:
  150. inner_table[i][j][0] = inner_table[i][j-1][0]
  151. inner_table[i][j][1] = inner_table[i][j-1][1]
  152. if inner_table[i][j][0]==pad_col:
  153. inner_table[i][j][0] = inner_table[i-1][j][0]
  154. inner_table[i][j][1] = inner_table[i-1][j][1]
  155. def repairTable(inner_table,dye_set = set(),key_set = set(),fix_value="~~"):
  156. '''
  157. @summary: 修复表头识别,将明显错误的进行修正
  158. '''
  159. def repairNeeded(line):
  160. first_1 = -1
  161. last_1 = -1
  162. first_0 = -1
  163. last_0 = -1
  164. count_1 = 0
  165. count_0 = 0
  166. for i in range(len(line)):
  167. if line[i][0]==fix_value:
  168. continue
  169. if line[i][1]==1:
  170. if first_1==-1:
  171. first_1 = i
  172. last_1 = i
  173. count_1 += 1
  174. if line[i][1]==0:
  175. if first_0 == -1:
  176. first_0 = i
  177. last_0 = i
  178. count_0 += 1
  179. if first_1 ==-1 or last_0 == -1:
  180. return False
  181. #异常情况:第一个不是表头;最后一个是表头;表头个数远大于属性值个数
  182. if first_1-0>0 or last_0-len(line)+1<0 or last_1==len(line)-1 or count_1-count_0>=3:
  183. return True
  184. return False
  185. def getsimilarity(line,line1):
  186. same_count = 0
  187. for item,item1 in zip(line,line1):
  188. if item[1]==item1[1]:
  189. same_count += 1
  190. return same_count/len(line)
  191. def selfrepair(inner_table,index,dye_set,key_set):
  192. '''
  193. @summary: 计算每个节点受到的挤压度来判断是否需要染色
  194. '''
  195. #print("B",inner_table[index])
  196. min_presure = 3
  197. list_dye = []
  198. first = None
  199. count = 0
  200. temp_set = set()
  201. _index = 0
  202. for item in inner_table[index]:
  203. if first is None:
  204. first = item[1]
  205. if item[0] not in temp_set:
  206. count += 1
  207. temp_set.add(item[0])
  208. else:
  209. if first == item[1]:
  210. if item[0] not in temp_set:
  211. temp_set.add(item[0])
  212. count += 1
  213. else:
  214. list_dye.append([first,count,_index])
  215. first = item[1]
  216. temp_set.add(item[0])
  217. count = 1
  218. _index += 1
  219. list_dye.append([first,count,_index])
  220. if len(list_dye)>1:
  221. begin = 0
  222. end = 0
  223. for i in range(len(list_dye)):
  224. end = list_dye[i][2]
  225. dye_flag = False
  226. #首尾要求压力减一
  227. if i==0:
  228. if list_dye[i+1][1]-list_dye[i][1]+1>=min_presure-1:
  229. dye_flag = True
  230. dye_type = list_dye[i+1][0]
  231. elif i==len(list_dye)-1:
  232. if list_dye[i-1][1]-list_dye[i][1]+1>=min_presure-1:
  233. dye_flag = True
  234. dye_type = list_dye[i-1][0]
  235. else:
  236. if list_dye[i][1]>1:
  237. if list_dye[i+1][1]-list_dye[i][1]+1>=min_presure:
  238. dye_flag = True
  239. dye_type = list_dye[i+1][0]
  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. else:
  244. if list_dye[i+1][1]+list_dye[i-1][1]-list_dye[i][1]+1>=min_presure:
  245. dye_flag = True
  246. dye_type = list_dye[i+1][0]
  247. 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 dye_flag:
  251. for h in range(begin,end):
  252. inner_table[index][h][1] = dye_type
  253. dye_set.add((inner_table[index][h][0],dye_type))
  254. key_set.add(inner_table[index][h][0])
  255. begin = end
  256. #print("E",inner_table[index])
  257. def otherrepair(inner_table,index,dye_set,key_set):
  258. list_provide_repair = []
  259. if index==0 and len(inner_table)>1:
  260. list_provide_repair.append(index+1)
  261. elif index==len(inner_table)-1:
  262. list_provide_repair.append(index-1)
  263. else:
  264. list_provide_repair.append(index+1)
  265. list_provide_repair.append(index-1)
  266. for provide_index in list_provide_repair:
  267. if not repairNeeded(inner_table[provide_index]):
  268. same_prob = getsimilarity(inner_table[index], inner_table[provide_index])
  269. if same_prob>=0.8:
  270. for i in range(len(inner_table[provide_index])):
  271. if inner_table[index][i][1]!=inner_table[provide_index][i][1]:
  272. dye_set.add((inner_table[index][i][0],inner_table[provide_index][i][1]))
  273. key_set.add(inner_table[index][i][0])
  274. inner_table[index][i][1] = inner_table[provide_index][i][1]
  275. elif same_prob<=0.2:
  276. for i in range(len(inner_table[provide_index])):
  277. if inner_table[index][i][1]==inner_table[provide_index][i][1]:
  278. dye_set.add((inner_table[index][i][0],inner_table[provide_index][i][1]))
  279. key_set.add(inner_table[index][i][0])
  280. inner_table[index][i][1] = 0 if inner_table[provide_index][i][1] ==1 else 1
  281. len_dye_set = len(dye_set)
  282. height = len(inner_table)
  283. for i in range(height):
  284. if repairNeeded(inner_table[i]):
  285. selfrepair(inner_table,i,dye_set,key_set)
  286. #otherrepair(inner_table,i,dye_set,key_set)
  287. for h in range(len(inner_table)):
  288. for w in range(len(inner_table[0])):
  289. if inner_table[h][w][0] in key_set:
  290. for item in dye_set:
  291. if inner_table[h][w][0]==item[0]:
  292. inner_table[h][w][1] = item[1]
  293. #如果两个set长度不相同,则有同一个key被反复染色,将导致无限迭代
  294. if len(dye_set)!=len(key_set):
  295. for i in range(height):
  296. if repairNeeded(inner_table[i]):
  297. selfrepair(inner_table,i,dye_set,key_set)
  298. #otherrepair(inner_table,i,dye_set,key_set)
  299. return
  300. if len(dye_set)==len_dye_set:
  301. '''
  302. for i in range(height):
  303. if repairNeeded(inner_table[i]):
  304. otherrepair(inner_table,i,dye_set,key_set)
  305. '''
  306. return
  307. repairTable(inner_table, dye_set, key_set)
  308. def sliceTable(inner_table,fix_value="~~"):
  309. #进行分块
  310. height = len(inner_table)
  311. width = len(inner_table[0])
  312. head_list = []
  313. head_list.append(0)
  314. last_head = None
  315. last_is_same_value = False
  316. for h in range(height):
  317. is_all_key = True#是否是全表头行
  318. is_all_value = True#是否是全属性值
  319. is_same_with_lastHead = True#和上一行的结构是否相同
  320. is_same_value=True#一行的item都一样
  321. #is_same_first_item = True#与上一行的第一项是否相同
  322. same_value = inner_table[h][0][0]
  323. for w in range(width):
  324. if last_head is not None:
  325. if inner_table[h-1][w][0]!=fix_value and inner_table[h-1][w][1] == 0:
  326. is_all_key = False
  327. if inner_table[h][w][0]==1:
  328. is_all_value = False
  329. if inner_table[h][w][1]!= inner_table[h-1][w][1]:
  330. is_same_with_lastHead = False
  331. if inner_table[h][w][0]!=fix_value and inner_table[h][w][0]!=same_value:
  332. is_same_value = False
  333. else:
  334. if re.search("\d+",same_value) is not None:
  335. is_same_value = False
  336. if h>0 and inner_table[h][0][0]!=inner_table[h-1][0][0]:
  337. is_same_first_item = False
  338. last_head = h
  339. if last_is_same_value:
  340. last_is_same_value = is_same_value
  341. continue
  342. if is_same_value:
  343. head_list.append(h)
  344. last_is_same_value = is_same_value
  345. continue
  346. if not is_all_key:
  347. if not is_same_with_lastHead:
  348. head_list.append(h)
  349. head_list.append(height)
  350. return head_list
  351. def setHead_initem(inner_table,pat_head,fix_value="~~",prob_min=0.5):
  352. set_item = set()
  353. height = len(inner_table)
  354. width = len(inner_table[0])
  355. empty_set = set()
  356. for i in range(height):
  357. for j in range(width):
  358. item = inner_table[i][j][0]
  359. if item.strip()=="":
  360. empty_set.add(item)
  361. else:
  362. set_item.add(item)
  363. list_item = list(set_item)
  364. if list_item:
  365. x = []
  366. for item in list_item:
  367. x.append(getPredictor("form").encode(item))
  368. predict_y = getPredictor("form").predict(np.array(x),type="item")
  369. _dict = dict()
  370. for item,values in zip(list_item,list(predict_y)):
  371. _dict[item] = values[1]
  372. # print("##",item,values)
  373. #print(_dict)
  374. for i in range(height):
  375. for j in range(width):
  376. item = inner_table[i][j][0]
  377. if item not in empty_set:
  378. 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)
  379. # print("=====")
  380. # for item in inner_table:
  381. # print(item)
  382. # print("======")
  383. repairTable(inner_table)
  384. head_list = sliceTable(inner_table)
  385. return inner_table,head_list
  386. def set_head_model(inner_table):
  387. for i in range(len(inner_table)):
  388. for j in range(len(inner_table[i])):
  389. # 删掉单格前后符号,以免影响表头预测
  390. col = inner_table[i][j][0]
  391. col = re.sub("^[^\u4e00-\u9fa5a-zA-Z0-9]+", "", col)
  392. col = re.sub("[^\u4e00-\u9fa5a-zA-Z0-9]+$", "", col)
  393. inner_table[i][j] = col
  394. # 模型预测表头
  395. predict_list = predict(inner_table)
  396. # 组合结果
  397. for i in range(len(inner_table)):
  398. for j in range(len(inner_table[i])):
  399. inner_table[i][j] = [inner_table[i][j], int(predict_list[i][j])]
  400. head_list = sliceTable(inner_table)
  401. return inner_table, head_list
  402. def setHead_incontext(inner_table,pat_head,fix_value="~~",prob_min=0.5):
  403. data_x,data_position = getPredictor("form").getModel("context").encode(inner_table)
  404. predict_y = getPredictor("form").getModel("context").predict(data_x)
  405. for _position,_y in zip(data_position,predict_y):
  406. _w = _position[0]
  407. _h = _position[1]
  408. if _y[1]>prob_min:
  409. inner_table[_h][_w][1] = 1
  410. else:
  411. inner_table[_h][_w][1] = 0
  412. _item = inner_table[_h][_w][0]
  413. if re.search(pat_head,_item) is not None and len(_item)<8:
  414. inner_table[_h][_w][1] = 1
  415. # print("=====")
  416. # for item in inner_table:
  417. # print(item)
  418. # print("======")
  419. height = len(inner_table)
  420. width = len(inner_table[0])
  421. for i in range(height):
  422. for j in range(width):
  423. if re.search("[::]$", inner_table[i][j][0]) and len(inner_table[i][j][0])<8:
  424. inner_table[i][j][1] = 1
  425. repairTable(inner_table)
  426. head_list = sliceTable(inner_table)
  427. # print("inner_table:",inner_table)
  428. return inner_table,head_list
  429. #设置表头
  430. def setHead_inline(inner_table,prob_min=0.64):
  431. pad_row = "@@"
  432. pad_col = "##"
  433. removePadding(inner_table, pad_row, pad_col)
  434. pad_pattern = re.compile(pad_row+"|"+pad_col)
  435. height = len(inner_table)
  436. width = len(inner_table[0])
  437. head_list = []
  438. head_list.append(0)
  439. #行表头
  440. is_head_last = False
  441. for i in range(height):
  442. is_head = False
  443. is_long_value = False
  444. #判断是否是全padding值
  445. is_same_value = True
  446. same_value = inner_table[i][0][0]
  447. for j in range(width):
  448. if inner_table[i][j][0]!=same_value and inner_table[i][j][0]!=pad_row:
  449. is_same_value = False
  450. break
  451. #predict is head or not with model
  452. temp_item = ""
  453. for j in range(width):
  454. temp_item += inner_table[i][j][0]+"|"
  455. temp_item = re.sub(pad_pattern,"",temp_item)
  456. form_prob = getPredictor("form").predict(formEncoding(temp_item,expand=True),type="line")
  457. if form_prob is not None:
  458. if form_prob[0][1]>prob_min:
  459. is_head = True
  460. else:
  461. is_head = False
  462. #print(temp_item,form_prob)
  463. if len(inner_table[i][0][0])>40:
  464. is_long_value = True
  465. if is_head or is_long_value or is_same_value:
  466. #不把连续表头分开
  467. if not is_head_last:
  468. head_list.append(i)
  469. if is_long_value or is_same_value:
  470. head_list.append(i+1)
  471. if is_head:
  472. for j in range(width):
  473. inner_table[i][j][1] = 1
  474. is_head_last = is_head
  475. head_list.append(height)
  476. #列表头
  477. for i in range(len(head_list)-1):
  478. head_begin = head_list[i]
  479. head_end = head_list[i+1]
  480. #最后一列不设置为列表头
  481. for i in range(width-1):
  482. is_head = False
  483. #predict is head or not with model
  484. temp_item = ""
  485. for j in range(head_begin,head_end):
  486. temp_item += inner_table[j][i][0]+"|"
  487. temp_item = re.sub(pad_pattern,"",temp_item)
  488. form_prob = getPredictor("form").predict(formEncoding(temp_item,expand=True),type="line")
  489. if form_prob is not None:
  490. if form_prob[0][1]>prob_min:
  491. is_head = True
  492. else:
  493. is_head = False
  494. if is_head:
  495. for j in range(head_begin,head_end):
  496. inner_table[j][i][1] = 2
  497. addPadding(inner_table, pad_row, pad_col)
  498. return inner_table,head_list
  499. #设置表头
  500. def setHead_withRule(inner_table,pattern,pat_value,count):
  501. height = len(inner_table)
  502. width = len(inner_table[0])
  503. head_list = []
  504. head_list.append(0)
  505. #行表头
  506. is_head_last = False
  507. for i in range(height):
  508. set_match = set()
  509. is_head = False
  510. is_long_value = False
  511. is_same_value = True
  512. same_value = inner_table[i][0][0]
  513. for j in range(width):
  514. if inner_table[i][j][0]!=same_value:
  515. is_same_value = False
  516. break
  517. for j in range(width):
  518. if re.search(pat_value,inner_table[i][j][0]) is not None:
  519. is_head = False
  520. break
  521. str_find = re.findall(pattern,inner_table[i][j][0])
  522. if len(str_find)>0:
  523. set_match.add(inner_table[i][j][0])
  524. if len(set_match)>=count:
  525. is_head = True
  526. if len(inner_table[i][0][0])>40:
  527. is_long_value = True
  528. if is_head or is_long_value or is_same_value:
  529. if not is_head_last:
  530. head_list.append(i)
  531. if is_head:
  532. for j in range(width):
  533. inner_table[i][j][1] = 1
  534. is_head_last = is_head
  535. head_list.append(height)
  536. #列表头
  537. for i in range(len(head_list)-1):
  538. head_begin = head_list[i]
  539. head_end = head_list[i+1]
  540. #最后一列不设置为列表头
  541. for i in range(width-1):
  542. set_match = set()
  543. is_head = False
  544. for j in range(head_begin,head_end):
  545. if re.search(pat_value,inner_table[j][i][0]) is not None:
  546. is_head = False
  547. break
  548. str_find = re.findall(pattern,inner_table[j][i][0])
  549. if len(str_find)>0:
  550. set_match.add(inner_table[j][i][0])
  551. if len(set_match)>=count:
  552. is_head = True
  553. if is_head:
  554. for j in range(head_begin,head_end):
  555. inner_table[j][i][1] = 2
  556. return inner_table,head_list
  557. #取得表格的处理方向
  558. def getDirect(inner_table,begin,end):
  559. '''
  560. column_head = set()
  561. row_head = set()
  562. widths = len(inner_table[0])
  563. for height in range(begin,end):
  564. for width in range(widths):
  565. if inner_table[height][width][1] ==1:
  566. row_head.add(height)
  567. if inner_table[height][width][1] ==2:
  568. column_head.add(width)
  569. company_pattern = re.compile("公司")
  570. if 0 in column_head and begin not in row_head:
  571. return "column"
  572. if 0 in column_head and begin in row_head:
  573. for height in range(begin,end):
  574. count = 0
  575. count_flag = True
  576. for width_index in range(width):
  577. if inner_table[height][width_index][1]==0:
  578. if re.search(company_pattern,inner_table[height][width_index][0]) is not None:
  579. count += 1
  580. else:
  581. count_flag = False
  582. if count_flag and count>=2:
  583. return "column"
  584. return "row"
  585. '''
  586. count_row_keys = 0
  587. count_column_keys = 0
  588. width = len(inner_table[0])
  589. if begin<end:
  590. for w in range(len(inner_table[begin])):
  591. if inner_table[begin][w][1]!=0:
  592. count_row_keys += 1
  593. for h in range(begin,end):
  594. if inner_table[h][0][1]!=0:
  595. count_column_keys += 1
  596. company_pattern = re.compile("有限(责任)?公司")
  597. for height in range(begin,end):
  598. count_set = set()
  599. count_flag = True
  600. for width_index in range(width):
  601. if inner_table[height][width_index][1]==0:
  602. if re.search(company_pattern,inner_table[height][width_index][0]) is not None:
  603. count_set.add(inner_table[height][width_index][0])
  604. else:
  605. count_flag = False
  606. if count_flag and len(count_set)>=2:
  607. return "column"
  608. # if count_column_keys>count_row_keys: #2022/2/15 此项不够严谨,造成很多错误,故取消
  609. # return "column"
  610. return "row"
  611. #根据表格处理方向生成句子,
  612. def getTableText(inner_table,head_list,key_direct=False):
  613. # packPattern = "(标包|[标包][号段名])"
  614. packPattern = "(标包|标的|[标包][号段名]|((项目|物资|设备|场次|标段|标的|产品)(名称)))" # 2020/11/23 大网站规则,补充采购类包名
  615. rankPattern = "(排名|排序|名次|序号|评标结果|评审结果|是否中标|推荐意见)" # 2020/11/23 大网站规则,添加序号为排序
  616. entityPattern = "((候选|([中投]标|报价))(单位|公司|人|供应商))"
  617. moneyPattern = "([中投]标|报价)(金额|价)"
  618. height = len(inner_table)
  619. width = len(inner_table[0])
  620. text = ""
  621. for head_i in range(len(head_list)-1):
  622. head_begin = head_list[head_i]
  623. head_end = head_list[head_i+1]
  624. direct = getDirect(inner_table, head_begin, head_end)
  625. #若只有一行,则直接按行读取
  626. if head_end-head_begin==1:
  627. text_line = ""
  628. for i in range(head_begin,head_end):
  629. for w in range(len(inner_table[i])):
  630. if inner_table[i][w][1]==1:
  631. _punctuation = ":"
  632. else:
  633. _punctuation = "," #2021/12/15 统一为中文标点,避免 206893924 国际F座1108,1,009,197.49元
  634. if w>0:
  635. if inner_table[i][w][0]!= inner_table[i][w-1][0]:
  636. text_line += inner_table[i][w][0]+_punctuation
  637. else:
  638. text_line += inner_table[i][w][0]+_punctuation
  639. text_line = text_line+"。" if text_line!="" else text_line
  640. text += text_line
  641. else:
  642. #构建一个共现矩阵
  643. table_occurence = []
  644. for i in range(head_begin,head_end):
  645. line_oc = []
  646. for j in range(width):
  647. cell = inner_table[i][j]
  648. line_oc.append({"text":cell[0],"type":cell[1],"occu_count":0,"left_head":"","top_head":"","left_dis":0,"top_dis":0})
  649. table_occurence.append(line_oc)
  650. occu_height = len(table_occurence)
  651. occu_width = len(table_occurence[0]) if len(table_occurence)>0 else 0
  652. #为每个属性值寻找表头
  653. for i in range(occu_height):
  654. for j in range(occu_width):
  655. cell = table_occurence[i][j]
  656. #是属性值
  657. if cell["type"]==0 and cell["text"]!="":
  658. left_head = ""
  659. top_head = ""
  660. find_flag = False
  661. temp_head = ""
  662. for loop_i in range(1,i+1):
  663. if not key_direct:
  664. key_values = [1,2]
  665. else:
  666. key_values = [1]
  667. if table_occurence[i-loop_i][j]["type"] in key_values:
  668. if find_flag:
  669. if table_occurence[i-loop_i][j]["text"]!=temp_head:
  670. top_head = table_occurence[i-loop_i][j]["text"]+":"+top_head
  671. else:
  672. top_head = table_occurence[i-loop_i][j]["text"]+":"+top_head
  673. find_flag = True
  674. temp_head = table_occurence[i-loop_i][j]["text"]
  675. table_occurence[i-loop_i][j]["occu_count"] += 1
  676. else:
  677. #找到表头后遇到属性值就返回
  678. if find_flag:
  679. break
  680. cell["top_head"] += top_head
  681. find_flag = False
  682. temp_head = ""
  683. for loop_j in range(1,j+1):
  684. if not key_direct:
  685. key_values = [1,2]
  686. else:
  687. key_values = [2]
  688. if table_occurence[i][j-loop_j]["type"] in key_values:
  689. if find_flag:
  690. if table_occurence[i][j-loop_j]["text"]!=temp_head:
  691. left_head = table_occurence[i][j-loop_j]["text"]+":"+left_head
  692. else:
  693. left_head = table_occurence[i][j-loop_j]["text"]+":"+left_head
  694. find_flag = True
  695. temp_head = table_occurence[i][j-loop_j]["text"]
  696. table_occurence[i][j-loop_j]["occu_count"] += 1
  697. else:
  698. if find_flag:
  699. break
  700. cell["left_head"] += left_head
  701. if direct=="row":
  702. for i in range(occu_height):
  703. pack_text = ""
  704. rank_text = ""
  705. entity_text = ""
  706. text_line = ""
  707. money_text = ""
  708. #在同一句话中重复的可以去掉
  709. text_set = set()
  710. for j in range(width):
  711. cell = table_occurence[i][j]
  712. if cell["type"]==0 or (cell["type"]==1 and cell["occu_count"]==0):
  713. cell = table_occurence[i][j]
  714. head = (cell["top_head"]+":") if len(cell["top_head"])>0 else ""
  715. if re.search("单报标限总]价|金额|成交报?价|报价", head):
  716. head = cell["left_head"] + head
  717. else:
  718. head += cell["left_head"]
  719. if str(head+cell["text"]) in text_set:
  720. continue
  721. if re.search(packPattern,head) is not None:
  722. pack_text += head+cell["text"]+","
  723. elif re.search(rankPattern,head) is not None: # 2020/11/23 大网站规则发现问题,if 改elif
  724. #排名替换为同一种表达
  725. rank_text += head+cell["text"]+","
  726. #print(rank_text)
  727. elif re.search(entityPattern,head) is not None:
  728. entity_text += head+cell["text"]+","
  729. #print(entity_text)
  730. else:
  731. if re.search(moneyPattern,head) is not None and entity_text!="":
  732. money_text += head+cell["text"]+","
  733. else:
  734. text_line += head+cell["text"]+","
  735. text_set.add(str(head+cell["text"]))
  736. text += pack_text+rank_text+entity_text+money_text+text_line
  737. text = text[:-1]+"。" if len(text)>0 else text
  738. else:
  739. for j in range(occu_width):
  740. pack_text = ""
  741. rank_text = ""
  742. entity_text = ""
  743. text_line = ""
  744. text_set = set()
  745. for i in range(occu_height):
  746. cell = table_occurence[i][j]
  747. if cell["type"]==0 or (cell["type"]==1 and cell["occu_count"]==0):
  748. cell = table_occurence[i][j]
  749. head = (cell["left_head"]+"") if len(cell["left_head"])>0 else ""
  750. if re.search("单报标限总]价|金额|成交报?价|报价", head):
  751. head = cell["top_head"] + head
  752. else:
  753. head += cell["top_head"]
  754. if str(head+cell["text"]) in text_set:
  755. continue
  756. if re.search(packPattern,head) is not None:
  757. pack_text += head+cell["text"]+","
  758. elif re.search(rankPattern,head) is not None: # 2020/11/23 大网站规则发现问题,if 改elif
  759. #排名替换为同一种表达
  760. rank_text += head+cell["text"]+","
  761. #print(rank_text)
  762. elif re.search(entityPattern,head) is not None and \
  763. re.search('业绩|资格|条件',head)==None and re.search('业绩',cell["text"])==None : #2021/10/19 解决包含业绩的行调到前面问题
  764. entity_text += head+cell["text"]+","
  765. #print(entity_text)
  766. else:
  767. text_line += head+cell["text"]+","
  768. text_set.add(str(head+cell["text"]))
  769. text += pack_text+rank_text+entity_text+text_line
  770. text = text[:-1]+"。" if len(text)>0 else text
  771. # if direct=="row":
  772. # for i in range(head_begin,head_end):
  773. # pack_text = ""
  774. # rank_text = ""
  775. # entity_text = ""
  776. # text_line = ""
  777. # #在同一句话中重复的可以去掉
  778. # text_set = set()
  779. # for j in range(width):
  780. # cell = inner_table[i][j]
  781. # #是属性值
  782. # if cell[1]==0 and cell[0]!="":
  783. # head = ""
  784. #
  785. # find_flag = False
  786. # temp_head = ""
  787. # for loop_i in range(0,i+1-head_begin):
  788. # if not key_direct:
  789. # key_values = [1,2]
  790. # else:
  791. # key_values = [1]
  792. # if inner_table[i-loop_i][j][1] in key_values:
  793. # if find_flag:
  794. # if inner_table[i-loop_i][j][0]!=temp_head:
  795. # head = inner_table[i-loop_i][j][0]+":"+head
  796. # else:
  797. # head = inner_table[i-loop_i][j][0]+":"+head
  798. # find_flag = True
  799. # temp_head = inner_table[i-loop_i][j][0]
  800. # else:
  801. # #找到表头后遇到属性值就返回
  802. # if find_flag:
  803. # break
  804. #
  805. # find_flag = False
  806. # temp_head = ""
  807. #
  808. #
  809. #
  810. # for loop_j in range(1,j+1):
  811. # if not key_direct:
  812. # key_values = [1,2]
  813. # else:
  814. # key_values = [2]
  815. # if inner_table[i][j-loop_j][1] in key_values:
  816. # if find_flag:
  817. # if inner_table[i][j-loop_j][0]!=temp_head:
  818. # head = inner_table[i][j-loop_j][0]+":"+head
  819. # else:
  820. # head = inner_table[i][j-loop_j][0]+":"+head
  821. # find_flag = True
  822. # temp_head = inner_table[i][j-loop_j][0]
  823. # else:
  824. # if find_flag:
  825. # break
  826. #
  827. # if str(head+inner_table[i][j][0]) in text_set:
  828. # continue
  829. # if re.search(packPattern,head) is not None:
  830. # pack_text += head+inner_table[i][j][0]+","
  831. # elif re.search(rankPattern,head) is not None: # 2020/11/23 大网站规则发现问题,if 改elif
  832. # #排名替换为同一种表达
  833. # rank_text += head+inner_table[i][j][0]+","
  834. # #print(rank_text)
  835. # elif re.search(entityPattern,head) is not None:
  836. # entity_text += head+inner_table[i][j][0]+","
  837. # #print(entity_text)
  838. # else:
  839. # text_line += head+inner_table[i][j][0]+","
  840. # text_set.add(str(head+inner_table[i][j][0]))
  841. # text += pack_text+rank_text+entity_text+text_line
  842. # text = text[:-1]+"。" if len(text)>0 else text
  843. # else:
  844. # for j in range(width):
  845. #
  846. # rank_text = ""
  847. # entity_text = ""
  848. # text_line = ""
  849. # text_set = set()
  850. # for i in range(head_begin,head_end):
  851. # cell = inner_table[i][j]
  852. # #是属性值
  853. # if cell[1]==0 and cell[0]!="":
  854. # find_flag = False
  855. # head = ""
  856. # temp_head = ""
  857. #
  858. # for loop_j in range(1,j+1):
  859. # if not key_direct:
  860. # key_values = [1,2]
  861. # else:
  862. # key_values = [2]
  863. # if inner_table[i][j-loop_j][1] in key_values:
  864. # if find_flag:
  865. # if inner_table[i][j-loop_j][0]!=temp_head:
  866. # head = inner_table[i][j-loop_j][0]+":"+head
  867. # else:
  868. # head = inner_table[i][j-loop_j][0]+":"+head
  869. # find_flag = True
  870. # temp_head = inner_table[i][j-loop_j][0]
  871. # else:
  872. # if find_flag:
  873. # break
  874. # find_flag = False
  875. # temp_head = ""
  876. # for loop_i in range(0,i+1-head_begin):
  877. # if not key_direct:
  878. # key_values = [1,2]
  879. # else:
  880. # key_values = [1]
  881. # if inner_table[i-loop_i][j][1] in key_values:
  882. # if find_flag:
  883. # if inner_table[i-loop_i][j][0]!=temp_head:
  884. # head = inner_table[i-loop_i][j][0]+":"+head
  885. # else:
  886. # head = inner_table[i-loop_i][j][0]+":"+head
  887. # find_flag = True
  888. # temp_head = inner_table[i-loop_i][j][0]
  889. # else:
  890. # if find_flag:
  891. # break
  892. # if str(head+inner_table[i][j][0]) in text_set:
  893. # continue
  894. # if re.search(rankPattern,head) is not None:
  895. # rank_text += head+inner_table[i][j][0]+","
  896. # #print(rank_text)
  897. # elif re.search(entityPattern,head) is not None:
  898. # entity_text += head+inner_table[i][j][0]+","
  899. # #print(entity_text)
  900. # else:
  901. # text_line += head+inner_table[i][j][0]+","
  902. # text_set.add(str(head+inner_table[i][j][0]))
  903. # text += rank_text+entity_text+text_line
  904. # text = text[:-1]+"。" if len(text)>0 else text
  905. return text
  906. def removeFix(inner_table,fix_value="~~"):
  907. height = len(inner_table)
  908. width = len(inner_table[0])
  909. for h in range(height):
  910. for w in range(width):
  911. if inner_table[h][w][0]==fix_value:
  912. inner_table[h][w][0] = ""
  913. def trunTable(tbody,in_attachment):
  914. # print(tbody.find('tbody'))
  915. # 附件中的表格,排除异常错乱的表格
  916. if in_attachment:
  917. if tbody.name=='table':
  918. _tbody = tbody.find('tbody')
  919. if _tbody is None:
  920. _tbody = tbody
  921. else:
  922. _tbody = tbody
  923. _td_len_list = []
  924. for _tr in _tbody.find_all(recursive=False):
  925. len_td = len(_tr.find_all(recursive=False))
  926. _td_len_list.append(len_td)
  927. if len(list(set(_td_len_list)))>8:
  928. return None
  929. fixSpan(tbody)
  930. inner_table = getTable(tbody)
  931. inner_table = fixTable(inner_table)
  932. if len(inner_table)>0 and len(inner_table[0])>0:
  933. #inner_table,head_list = setHead_withRule(inner_table,pat_head,pat_value,3)
  934. #inner_table,head_list = setHead_inline(inner_table)
  935. # inner_table, head_list = setHead_initem(inner_table,pat_head)
  936. inner_table, head_list = set_head_model(inner_table)
  937. # inner_table,head_list = setHead_incontext(inner_table,pat_head)
  938. # print("table_head", inner_table)
  939. # for begin in range(len(head_list[:-1])):
  940. # for item in inner_table[head_list[begin]:head_list[begin+1]]:
  941. # print(item)
  942. # print("====")
  943. removeFix(inner_table)
  944. # print("----")
  945. # print(head_list)
  946. # for item in inner_table:
  947. # print(item)
  948. tbody.string = getTableText(inner_table,head_list)
  949. table_max_len = 30000
  950. tbody.string = tbody.string[:table_max_len]
  951. #print(tbody.string)
  952. tbody.name = "turntable"
  953. return inner_table
  954. return None
  955. pat_head = re.compile('^(名称|序号|项目|标项|工程|品目[一二三四1234]|第[一二三四1234](标段|名|候选人|中标)|包段|标包|分包|包号|货物|单位|数量|价格|报价|金额|总价|单价|[招投中]标|候选|编号|得分|评委|评分|名次|排名|排序|科室|方式|工期|时间|产品|开始|结束|联系|日期|面积|姓名|证号|备注|级别|地[点址]|类型|代理|制造|企业资质|质量目标|工期目标|(需求|服务|项目|施工|采购|招租|出租|转让|出让|业主|询价|委托|权属|招标|竞得|抽取|承建)(人|方|单位)(名称)?|(供应商|供货商|服务商)(名称)?)$')
  956. #pat_head = re.compile('(名称|序号|项目|工程|品目[一二三四1234]|第[一二三四1234](标段|候选人|中标)|包段|包号|货物|单位|数量|价格|报价|金额|总价|单价|[招投中]标|供应商|候选|编号|得分|评委|评分|名次|排名|排序|科室|方式|工期|时间|产品|开始|结束|联系|日期|面积|姓名|证号|备注|级别|地[点址]|类型|代理)')
  957. pat_value = re.compile("(\d{2,}.\d{1}|\d+年\d+月|\d{8,}|\d{3,}-\d{6,}|有限[责任]*公司|^\d+$)")
  958. list_innerTable = []
  959. # 2022/2/9 删除干扰标签
  960. for tag in soup.find_all('option'): #例子: 216661412
  961. if 'selected' not in tag.attrs:
  962. tag.extract()
  963. for ul in soup.find_all('ul'): #例子 156439663 多个不同channel 类别的标题
  964. if ul.find_all('li') == ul.findChildren(recursive=False) and len(set(re.findall(
  965. '招标公告|中标结果公示|中标候选人公示|招标答疑|开标评标|合同履?约?公示|开标评标|资格评审',
  966. ul.get_text(), re.S)))>3:
  967. ul.extract()
  968. # tbodies = soup.find_all('table')
  969. # 遍历表格中的每个tbody
  970. tbodies = []
  971. in_attachment = False
  972. for _part in soup.find_all():
  973. if _part.name=='table':
  974. tbodies.append((_part,in_attachment))
  975. elif _part.name=='div':
  976. if 'class' in _part.attrs and "richTextFetch" in _part['class']:
  977. in_attachment = True
  978. #逆序处理嵌套表格
  979. for tbody_index in range(1,len(tbodies)+1):
  980. tbody,_in_attachment = tbodies[len(tbodies)-tbody_index]
  981. inner_table = trunTable(tbody,_in_attachment)
  982. list_innerTable.append(inner_table)
  983. # tbodies = soup.find_all('tbody')
  984. # 遍历表格中的每个tbody
  985. tbodies = []
  986. in_attachment = False
  987. for _part in soup.find_all():
  988. if _part.name == 'tbody':
  989. tbodies.append((_part, in_attachment))
  990. elif _part.name == 'div':
  991. if 'class' in _part.attrs and "richTextFetch" in _part['class']:
  992. in_attachment = True
  993. #逆序处理嵌套表格
  994. for tbody_index in range(1,len(tbodies)+1):
  995. tbody,_in_attachment = tbodies[len(tbodies)-tbody_index]
  996. inner_table = trunTable(tbody,_in_attachment)
  997. list_innerTable.append(inner_table)
  998. return soup
  999. # return list_innerTable
  1000. re_num = re.compile("[二三四五六七八九]十[一二三四五六七八九]?|十[一二三四五六七八九]|[一二三四五六七八九十]")
  1001. num_dict = {
  1002. "一": 1, "二": 2,
  1003. "三": 3, "四": 4,
  1004. "五": 5, "六": 6,
  1005. "七": 7, "八": 8,
  1006. "九": 9, "十": 10}
  1007. # 一百以内的中文大写转换为数字
  1008. def change2num(text):
  1009. result_num = -1
  1010. # text = text[:6]
  1011. match = re_num.search(text)
  1012. if match:
  1013. _num = match.group()
  1014. if num_dict.get(_num):
  1015. return num_dict.get(_num)
  1016. else:
  1017. tenths = 1
  1018. the_unit = 0
  1019. num_split = _num.split("十")
  1020. if num_dict.get(num_split[0]):
  1021. tenths = num_dict.get(num_split[0])
  1022. if num_dict.get(num_split[1]):
  1023. the_unit = num_dict.get(num_split[1])
  1024. result_num = tenths * 10 + the_unit
  1025. elif re.search("\d{1,2}",text):
  1026. _num = re.search("\d{1,2}",text).group()
  1027. result_num = int(_num)
  1028. return result_num
  1029. #大纲分段处理
  1030. def get_preprocessed_outline(soup):
  1031. pattern_0 = re.compile("^(?:[二三四五六七八九]十[一二三四五六七八九]?|十[一二三四五六七八九]|[一二三四五六七八九十])[、.\.]")
  1032. pattern_1 = re.compile("^[\((]?(?:[二三四五六七八九]十[一二三四五六七八九]?|十[一二三四五六七八九]|[一二三四五六七八九十])[\))]")
  1033. pattern_2 = re.compile("^\d{1,2}[、.\.](?=[^\d]{1,2}|$)")
  1034. pattern_3 = re.compile("^[\((]?\d{1,2}[\))]")
  1035. pattern_list = [pattern_0, pattern_1, pattern_2, pattern_3]
  1036. body = soup.find("body")
  1037. body_child = body.find_all(recursive=False)
  1038. deal_part = body
  1039. # print(body_child[0]['id'])
  1040. if 'id' in body_child[0].attrs:
  1041. if len(body_child) <= 2 and body_child[0]['id'] == 'pcontent':
  1042. deal_part = body_child[0]
  1043. if len(deal_part.find_all(recursive=False))>2:
  1044. deal_part = deal_part.parent
  1045. skip_tag = ['turntable', 'tbody', 'th', 'tr', 'td', 'table','thead','tfoot']
  1046. for part in deal_part.find_all(recursive=False):
  1047. # 查找解析文本的主干部分
  1048. is_main_text = False
  1049. through_text_num = 0
  1050. while (not is_main_text and part.find_all(recursive=False)):
  1051. while len(part.find_all(recursive=False)) == 1 and part.get_text(strip=True) == \
  1052. part.find_all(recursive=False)[0].get_text(strip=True):
  1053. part = part.find_all(recursive=False)[0]
  1054. max_len = len(part.get_text(strip=True))
  1055. is_main_text = True
  1056. for t_part in part.find_all(recursive=False):
  1057. if t_part.name not in skip_tag and t_part.get_text(strip=True)!="":
  1058. through_text_num += 1
  1059. if t_part.get_text(strip=True)!="" and len(t_part.get_text(strip=True))/max_len>=0.65:
  1060. if t_part.name not in skip_tag:
  1061. is_main_text = False
  1062. part = t_part
  1063. break
  1064. else:
  1065. while len(t_part.find_all(recursive=False)) == 1 and t_part.get_text(strip=True) == \
  1066. t_part.find_all(recursive=False)[0].get_text(strip=True):
  1067. t_part = t_part.find_all(recursive=False)[0]
  1068. if through_text_num>2:
  1069. is_table = True
  1070. for _t_part in t_part.find_all(recursive=False):
  1071. if _t_part.name not in skip_tag:
  1072. is_table = False
  1073. break
  1074. if not is_table:
  1075. is_main_text = False
  1076. part = t_part
  1077. break
  1078. else:
  1079. is_main_text = False
  1080. part = t_part
  1081. break
  1082. is_find = False
  1083. for _pattern in pattern_list:
  1084. last_index = 0
  1085. handle_list = []
  1086. for _part in part.find_all(recursive=False):
  1087. if _part.name not in skip_tag and _part.get_text(strip=True) != "":
  1088. # print('text:', _part.get_text(strip=True))
  1089. re_match = re.search(_pattern, _part.get_text(strip=True))
  1090. if re_match:
  1091. outline_index = change2num(re_match.group())
  1092. if last_index < outline_index:
  1093. # _part.insert_before("##split##")
  1094. handle_list.append(_part)
  1095. last_index = outline_index
  1096. if len(handle_list)>1:
  1097. is_find = True
  1098. for _part in handle_list:
  1099. _part.insert_before("##split##")
  1100. if is_find:
  1101. break
  1102. # print(soup)
  1103. return soup
  1104. #数据清洗
  1105. def segment(soup,final=True):
  1106. # print("==")
  1107. # print(soup)
  1108. # print("====")
  1109. #segList = ["tr","div","h1", "h2", "h3", "h4", "h5", "h6", "header"]
  1110. subspaceList = ["td",'a',"span","p"]
  1111. if soup.name in subspaceList:
  1112. #判断有值叶子节点数
  1113. _count = 0
  1114. for child in soup.find_all(recursive=True):
  1115. if child.get_text().strip()!="" and len(child.find_all())==0:
  1116. _count += 1
  1117. if _count<=1:
  1118. text = soup.get_text()
  1119. # 2020/11/24 大网站规则添加
  1120. if 'title' in soup.attrs:
  1121. if '...' in soup.get_text() and soup.get_text().strip()[:-3] in soup.attrs['title']:
  1122. text = soup.attrs['title']
  1123. _list = []
  1124. for x in re.split("\s+",text):
  1125. if x.strip()!="":
  1126. _list.append(len(x))
  1127. if len(_list)>0:
  1128. _minLength = min(_list)
  1129. if _minLength>2:
  1130. _substr = ","
  1131. else:
  1132. _substr = ""
  1133. else:
  1134. _substr = ""
  1135. text = text.replace("\r\n",",").replace("\n",",")
  1136. text = re.sub("\s+",_substr,text)
  1137. # text = re.sub("\s+","##space##",text)
  1138. return text
  1139. segList = ["title"]
  1140. commaList = ["div","br","td","p","li"]
  1141. #commaList = []
  1142. spaceList = ["span"]
  1143. tbodies = soup.find_all('tbody')
  1144. if len(tbodies) == 0:
  1145. tbodies = soup.find_all('table')
  1146. # 递归遍历所有节点,插入符号
  1147. for child in soup.find_all(recursive=True):
  1148. # print(child.name,child.get_text())
  1149. if child.name in segList:
  1150. child.insert_after("。")
  1151. if child.name in commaList:
  1152. child.insert_after(",")
  1153. # if child.name == 'div' and 'class' in child.attrs:
  1154. # # 添加附件"attachment"标识
  1155. # if "richTextFetch" in child['class']:
  1156. # child.insert_before("##attachment##")
  1157. # print(child.parent)
  1158. # if child.name in subspaceList:
  1159. # child.insert_before("#subs"+str(child.name)+"#")
  1160. # child.insert_after("#sube"+str(child.name)+"#")
  1161. # if child.name in spaceList:
  1162. # child.insert_after(" ")
  1163. text = str(soup.get_text())
  1164. #替换英文冒号为中文冒号
  1165. text = re.sub("(?<=[\u4e00-\u9fa5]):|:(?=[\u4e00-\u9fa5])",":",text)
  1166. #替换为中文逗号
  1167. text = re.sub("(?<=[\u4e00-\u9fa5]),|,(?=[\u4e00-\u9fa5])",",",text)
  1168. #替换为中文分号
  1169. text = re.sub("(?<=[\u4e00-\u9fa5]);|;(?=[\u4e00-\u9fa5])",";",text)
  1170. # 感叹号替换为中文句号
  1171. text = re.sub("(?<=[\u4e00-\u9fa5])[!!]|[!!](?=[\u4e00-\u9fa5])","。",text)
  1172. #替换格式未识别的问号为" " ,update:2021/7/20
  1173. text = re.sub("[?\?]{2,}"," ",text)
  1174. #替换"""为"“",否则导入deepdive出错
  1175. # text = text.replace('"',"“").replace("\r","").replace("\n",",")
  1176. text = text.replace('"',"“").replace("\r","").replace("\n","") #2022/1/4修复 非分段\n 替换为逗号造成 公司拆分 span \n南航\n上海\n分公司
  1177. # print('==1',text)
  1178. # text = re.sub("\s{4,}",",",text)
  1179. # 解决公告中的" "空格替换问题
  1180. if re.search("\s{4,}",text):
  1181. _text = ""
  1182. for _sent in re.split("。+",text):
  1183. for _sent2 in re.split(',+',_sent):
  1184. for _sent3 in re.split(":+",_sent2):
  1185. for _t in re.split("\s{4,}",_sent3):
  1186. if len(_t)<3:
  1187. _text += _t
  1188. else:
  1189. _text += ","+_t
  1190. _text += ":"
  1191. _text = _text[:-1]
  1192. _text += ","
  1193. _text = _text[:-1]
  1194. _text += "。"
  1195. _text = _text[:-1]
  1196. text = _text
  1197. # print('==2',text)
  1198. #替换标点
  1199. #替换连续的标点
  1200. if final:
  1201. text = re.sub("##space##"," ",text)
  1202. punc_pattern = "(?P<del>[。,;::,\s]+)"
  1203. list_punc = re.findall(punc_pattern,text)
  1204. list_punc.sort(key=lambda x:len(x),reverse=True)
  1205. for punc_del in list_punc:
  1206. if len(punc_del)>1:
  1207. if len(punc_del.strip())>0:
  1208. if ":" in punc_del.strip():
  1209. if "。" in punc_del.strip():
  1210. text = re.sub(punc_del, ":。", text)
  1211. else:
  1212. text = re.sub(punc_del,":",text)
  1213. else:
  1214. text = re.sub(punc_del,punc_del.strip()[0],text) #2021/12/09 修正由于某些标签后插入符号把原来符号替换
  1215. else:
  1216. text = re.sub(punc_del,"",text)
  1217. #将连续的中文句号替换为一个
  1218. text_split = text.split("。")
  1219. text_split = [x for x in text_split if len(x)>0]
  1220. text = "。".join(text_split)
  1221. # #删除标签中的所有空格
  1222. # for subs in subspaceList:
  1223. # patten = "#subs"+str(subs)+"#(.*?)#sube"+str(subs)+"#"
  1224. # while(True):
  1225. # oneMatch = re.search(re.compile(patten),text)
  1226. # if oneMatch is not None:
  1227. # _match = oneMatch.group(1)
  1228. # text = text.replace("#subs"+str(subs)+"#"+_match+"#sube"+str(subs)+"#",_match)
  1229. # else:
  1230. # break
  1231. # text过大报错
  1232. LOOP_LEN = 10000
  1233. LOOP_BEGIN = 0
  1234. _text = ""
  1235. if len(text)<10000000:
  1236. while(LOOP_BEGIN<len(text)):
  1237. _text += re.sub(")",")",re.sub("(","(",re.sub("\s+","",text[LOOP_BEGIN:LOOP_BEGIN+LOOP_LEN])))
  1238. LOOP_BEGIN += LOOP_LEN
  1239. text = _text
  1240. # 附件标识前修改为句号,避免正文和附件内容混合在一起
  1241. text = re.sub("[^。](?=##attachment##)","。",text)
  1242. text = re.sub("[^。](?=##attachment_begin##)","。",text)
  1243. text = re.sub("[^。](?=##attachment_end##)","。",text)
  1244. text = re.sub("##attachment_begin##。","##attachment_begin##",text)
  1245. text = re.sub("##attachment_end##。","##attachment_end##",text)
  1246. return text
  1247. '''
  1248. #数据清洗
  1249. def segment(soup):
  1250. segList = ["title"]
  1251. commaList = ["p","div","h1", "h2", "h3", "h4", "h5", "h6", "header", "dl", "ul", "label"]
  1252. spaceList = ["span"]
  1253. tbodies = soup.find_all('tbody')
  1254. if len(tbodies) == 0:
  1255. tbodies = soup.find_all('table')
  1256. # 递归遍历所有节点,插入符号
  1257. for child in soup.find_all(recursive=True):
  1258. if child.name == 'br':
  1259. child.insert_before(',')
  1260. child_text = re.sub('\s', '', child.get_text())
  1261. if child_text == '' or child_text[-1] in ['。',',',':',';']:
  1262. continue
  1263. if child.name in segList:
  1264. child.insert_after("。")
  1265. if child.name in commaList:
  1266. if len(child_text)>3 and len(child_text) <50: # 先判断是否字数少于50,成立加逗号,否则加句号
  1267. child.insert_after(",")
  1268. elif len(child_text) >=50:
  1269. child.insert_after("。")
  1270. #if child.name in spaceList:
  1271. #child.insert_after(" ")
  1272. text = str(soup.get_text())
  1273. text = re.sub("\s{5,}",",",text)
  1274. text = text.replace('"',"“").replace("\r","").replace("\n",",")
  1275. #替换"""为"“",否则导入deepdive出错
  1276. text = text.replace('"',"“")
  1277. #text = text.replace('"',"“").replace("\r","").replace("\n","")
  1278. #删除所有空格
  1279. text = re.sub("\s+","#nbsp#",text)
  1280. text_list = text.split('#nbsp#')
  1281. new_text = ''
  1282. for i in range(len(text_list)-1):
  1283. if text_list[i] == '' or text_list[i][-1] in [',','。',';',':']:
  1284. new_text += text_list[i]
  1285. elif re.findall('([一二三四五六七八九]、)', text_list[i+1][:4]) != []:
  1286. new_text += text_list[i] + '。'
  1287. elif re.findall('([0-9]、)', text_list[i+1][:4]) != []:
  1288. new_text += text_list[i] + ';'
  1289. elif text_list[i].isdigit() and text_list[i+1].isdigit():
  1290. new_text += text_list[i] + ' '
  1291. elif text_list[i][-1] in ['-',':','(',')','/','(',')','——','年','月','日','时','分','¥'] or text_list[i+1][0] in ['-',':','(',')','/','(',')','——','年','月','日','时','分','元','万元']:
  1292. new_text += text_list[i]
  1293. elif len(text_list[i]) >= 3 and len(text_list[i+1]) >= 3:
  1294. new_text += text_list[i] + ','
  1295. else:
  1296. new_text += text_list[i]
  1297. new_text += text_list[-1]
  1298. text = new_text
  1299. #替换英文冒号为中文冒号
  1300. text = re.sub("(?<=[\u4e00-\u9fa5]):|:(?=[\u4e00-\u9fa5])",":",text)
  1301. #替换为中文逗号
  1302. text = re.sub("(?<=[\u4e00-\u9fa5]),|,(?=[\u4e00-\u9fa5])",",",text)
  1303. #替换为中文分号
  1304. text = re.sub("(?<=[\u4e00-\u9fa5]);|;(?=[\u4e00-\u9fa5])",";",text)
  1305. #替换标点
  1306. while(True):
  1307. #替换连续的标点
  1308. punc = re.search(",(?P<punc>:|。|,|;)\s*",text)
  1309. if punc is not None:
  1310. text = re.sub(","+punc.group("punc")+"\s*",punc.group("punc"),text)
  1311. punc = re.search("(?P<punc>:|。|,|;)\s*,",text)
  1312. if punc is not None:
  1313. text = re.sub(punc.group("punc")+"\s*,",punc.group("punc"),text)
  1314. else:
  1315. #替换标点之后的空格
  1316. punc = re.search("(?P<punc>:|。|,|;)\s+",text)
  1317. if punc is not None:
  1318. text = re.sub(punc.group("punc")+"\s+",punc.group("punc"),text)
  1319. else:
  1320. break
  1321. #将连续的中文句号替换为一个
  1322. text_split = text.split("。")
  1323. text_split = [x for x in text_split if len(x)>0]
  1324. text = "。".join(text_split)
  1325. #替换中文括号为英文括号
  1326. text = re.sub("(","(",text)
  1327. text = re.sub(")",")",text)
  1328. return text
  1329. '''
  1330. #连续实体合并(弃用)
  1331. def union_ner(list_ner):
  1332. result_list = []
  1333. union_index = []
  1334. union_index_set = set()
  1335. for i in range(len(list_ner)-1):
  1336. if len(set([str(list_ner[i][2]),str(list_ner[i+1][2])])&set(["org","company"]))==2:
  1337. if list_ner[i][1]-list_ner[i+1][0]==1:
  1338. union_index_set.add(i)
  1339. union_index_set.add(i+1)
  1340. union_index.append((i,i+1))
  1341. for i in range(len(list_ner)):
  1342. if i not in union_index_set:
  1343. result_list.append(list_ner[i])
  1344. for item in union_index:
  1345. #print(str(list_ner[item[0]][3])+str(list_ner[item[1]][3]))
  1346. 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])))
  1347. return result_list
  1348. # def get_preprocessed(articles,useselffool=False):
  1349. # '''
  1350. # @summary:预处理步骤,NLP处理、实体识别
  1351. # @param:
  1352. # articles:待处理的文章list [[id,source,jointime,doc_id,title]]
  1353. # @return:list of articles,list of each article of sentences,list of each article of entitys
  1354. # '''
  1355. # list_articles = []
  1356. # list_sentences = []
  1357. # list_entitys = []
  1358. # cost_time = dict()
  1359. # for article in articles:
  1360. # list_sentences_temp = []
  1361. # list_entitys_temp = []
  1362. # doc_id = article[0]
  1363. # sourceContent = article[1]
  1364. # _send_doc_id = article[3]
  1365. # _title = article[4]
  1366. # #表格处理
  1367. # key_preprocess = "tableToText"
  1368. # start_time = time.time()
  1369. # article_processed = segment(tableToText(BeautifulSoup(sourceContent,"lxml")))
  1370. #
  1371. # # log(article_processed)
  1372. #
  1373. # if key_preprocess not in cost_time:
  1374. # cost_time[key_preprocess] = 0
  1375. # cost_time[key_preprocess] += time.time()-start_time
  1376. #
  1377. # #article_processed = article[1]
  1378. # list_articles.append(Article(doc_id,article_processed,sourceContent,_send_doc_id,_title))
  1379. # #nlp处理
  1380. # if article_processed is not None and len(article_processed)!=0:
  1381. # split_patten = "。"
  1382. # sentences = []
  1383. # _begin = 0
  1384. # for _iter in re.finditer(split_patten,article_processed):
  1385. # sentences.append(article_processed[_begin:_iter.span()[1]])
  1386. # _begin = _iter.span()[1]
  1387. # sentences.append(article_processed[_begin:])
  1388. #
  1389. # lemmas = []
  1390. # doc_offsets = []
  1391. # dep_types = []
  1392. # dep_tokens = []
  1393. #
  1394. # time1 = time.time()
  1395. #
  1396. # '''
  1397. # tokens_all = fool.cut(sentences)
  1398. # #pos_all = fool.LEXICAL_ANALYSER.pos(tokens_all)
  1399. # #ner_tag_all = fool.LEXICAL_ANALYSER.ner_labels(sentences,tokens_all)
  1400. # ner_entitys_all = fool.ner(sentences)
  1401. # '''
  1402. # #限流执行
  1403. # key_nerToken = "nerToken"
  1404. # start_time = time.time()
  1405. # tokens_all,ner_entitys_all = getTokensAndNers(sentences,useselffool=useselffool)
  1406. # if key_nerToken not in cost_time:
  1407. # cost_time[key_nerToken] = 0
  1408. # cost_time[key_nerToken] += time.time()-start_time
  1409. #
  1410. #
  1411. # for sentence_index in range(len(sentences)):
  1412. #
  1413. #
  1414. #
  1415. # list_sentence_entitys = []
  1416. # sentence_text = sentences[sentence_index]
  1417. # tokens = tokens_all[sentence_index]
  1418. #
  1419. # list_tokenbegin = []
  1420. # begin = 0
  1421. # for i in range(0,len(tokens)):
  1422. # list_tokenbegin.append(begin)
  1423. # begin += len(str(tokens[i]))
  1424. # list_tokenbegin.append(begin+1)
  1425. # #pos_tag = pos_all[sentence_index]
  1426. # pos_tag = ""
  1427. #
  1428. # ner_entitys = ner_entitys_all[sentence_index]
  1429. #
  1430. # 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))
  1431. #
  1432. # #识别package
  1433. #
  1434. #
  1435. # #识别实体
  1436. # for ner_entity in ner_entitys:
  1437. # begin_index_temp = ner_entity[0]
  1438. # end_index_temp = ner_entity[1]
  1439. # entity_type = ner_entity[2]
  1440. # entity_text = ner_entity[3]
  1441. #
  1442. # for j in range(len(list_tokenbegin)):
  1443. # if list_tokenbegin[j]==begin_index_temp:
  1444. # begin_index = j
  1445. # break
  1446. # elif list_tokenbegin[j]>begin_index_temp:
  1447. # begin_index = j-1
  1448. # break
  1449. # begin_index_temp += len(str(entity_text))
  1450. # for j in range(begin_index,len(list_tokenbegin)):
  1451. # if list_tokenbegin[j]>=begin_index_temp:
  1452. # end_index = j-1
  1453. # break
  1454. # entity_id = "%s_%d_%d_%d"%(doc_id,sentence_index,begin_index,end_index)
  1455. #
  1456. # #去掉标点符号
  1457. # entity_text = re.sub("[,,。:]","",entity_text)
  1458. # 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))
  1459. #
  1460. #
  1461. # #使用正则识别金额
  1462. # entity_type = "money"
  1463. #
  1464. # #money_patten_str = "(([1-9][\d,,]*(?:\.\d+)?[百千万亿]?[\(\)()元整]+)|([零壹贰叁肆伍陆柒捌玖拾佰仟萬億十百千万亿元角分]{3,})|(?:[¥¥]+,?|报价|标价)[(\(]?([万])?元?[)\)]?[::]?.{,7}?([1-9][\d,,]*(?:\.\d+)?(?:,?)[百千万亿]?)|([1-9][\d,,]*(?:\.\d+)?(?:,?)[百千万亿]?)[\((]?([万元]{1,2}))*"
  1465. #
  1466. # list_money_pattern = {"cn":"(()()([零壹贰叁肆伍陆柒捌玖拾佰仟萬億十百千万亿元角分]{3,})())*",
  1467. # "key_word":"((?:[¥¥]+,?|[报标限]价|金额)(?:[(\(]?\s*([万元]*)\s*[)\)]?)\s*[::]?(\s*[^壹贰叁肆伍陆柒捌玖拾佰仟萬億分]{,7}?)([0-9][\d,,]*(?:\.\d+)?(?:,?)[百千万亿元]*)())*",
  1468. # "front_m":"((?:[(\(]?\s*([万元]+)\s*[)\)])\s*[::]?(\s*[^壹贰叁肆伍陆柒捌玖拾佰仟萬億分]{,7}?)([0-9][\d,,]*(?:\.\d+)?(?:,?)[百千万亿元]*)())*",
  1469. # "behind_m":"(()()([0-9][\d,,]*(?:\.\d+)?(?:,?)[百千万亿]*)[\((]?([万元]+)[\))]?)*"}
  1470. #
  1471. # set_begin = set()
  1472. # for pattern_key in list_money_pattern.keys():
  1473. # pattern = re.compile(list_money_pattern[pattern_key])
  1474. # all_match = re.findall(pattern, sentence_text)
  1475. # index = 0
  1476. # for i in range(len(all_match)):
  1477. # if len(all_match[i][0])>0:
  1478. # # print("===",all_match[i])
  1479. # #print(all_match[i][0])
  1480. # unit = ""
  1481. # entity_text = all_match[i][3]
  1482. # if pattern_key in ["key_word","front_m"]:
  1483. # unit = all_match[i][1]
  1484. # else:
  1485. # unit = all_match[i][4]
  1486. # if entity_text.find("元")>=0:
  1487. # unit = ""
  1488. #
  1489. # index += len(all_match[i][0])-len(entity_text)-len(all_match[i][4])#-len(all_match[i][1])-len(all_match[i][2])#整个提出来的作为实体->数字部分作为整体,否则会丢失特征
  1490. #
  1491. # begin_index_temp = index
  1492. # for j in range(len(list_tokenbegin)):
  1493. # if list_tokenbegin[j]==index:
  1494. # begin_index = j
  1495. # break
  1496. # elif list_tokenbegin[j]>index:
  1497. # begin_index = j-1
  1498. # break
  1499. # index += len(str(entity_text))+len(all_match[i][4])#+len(all_match[i][2])+len(all_match[i][1])#整个提出来的作为实体
  1500. # end_index_temp = index
  1501. # #index += len(str(all_match[i][0]))
  1502. # for j in range(begin_index,len(list_tokenbegin)):
  1503. # if list_tokenbegin[j]>=index:
  1504. # end_index = j-1
  1505. # break
  1506. # entity_id = "%s_%d_%d_%d"%(doc_id,sentence_index,begin_index,end_index)
  1507. #
  1508. #
  1509. # entity_text = re.sub("[^0-9.零壹贰叁肆伍陆柒捌玖拾佰仟萬億十百千万亿元角分]","",entity_text)
  1510. # if len(unit)>0:
  1511. # entity_text = str(getUnifyMoney(entity_text)*getMultipleFactor(unit[0]))
  1512. # else:
  1513. # entity_text = str(getUnifyMoney(entity_text))
  1514. #
  1515. # _exists = False
  1516. # for item in list_sentence_entitys:
  1517. # if item.entity_id==entity_id and item.entity_type==entity_type:
  1518. # _exists = True
  1519. # if not _exists:
  1520. # if float(entity_text)>10:
  1521. # 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))
  1522. #
  1523. # else:
  1524. # index += 1
  1525. #
  1526. # list_sentence_entitys.sort(key=lambda x:x.begin_index)
  1527. # list_entitys_temp = list_entitys_temp+list_sentence_entitys
  1528. # list_sentences.append(list_sentences_temp)
  1529. # list_entitys.append(list_entitys_temp)
  1530. # return list_articles,list_sentences,list_entitys,cost_time
  1531. def get_preprocessed(articles, useselffool=False):
  1532. '''
  1533. @summary:预处理步骤,NLP处理、实体识别
  1534. @param:
  1535. articles:待处理的文章list [[id,source,jointime,doc_id,title]]
  1536. @return:list of articles,list of each article of sentences,list of each article of entitys
  1537. '''
  1538. cost_time = dict()
  1539. list_articles = get_preprocessed_article(articles,cost_time)
  1540. list_sentences,list_outlines = get_preprocessed_sentences(list_articles,True,cost_time)
  1541. list_entitys = get_preprocessed_entitys(list_sentences,True,cost_time)
  1542. calibrateEnterprise(list_articles,list_sentences,list_entitys)
  1543. return list_articles,list_sentences,list_entitys,list_outlines,cost_time
  1544. def special_treatment(sourceContent, web_source_no):
  1545. try:
  1546. if web_source_no == 'DX000202-1':
  1547. ser = re.search('中标供应商及中标金额:【((\w{5,20}-[\d,.]+,)+)】', sourceContent)
  1548. if ser:
  1549. new = ""
  1550. l = ser.group(1).split(',')
  1551. for i in range(len(l)):
  1552. it = l[i]
  1553. if '-' in it:
  1554. role, money = it.split('-')
  1555. new += '标段%d, 中标供应商: ' % (i + 1) + role + ',中标金额:' + money + '。'
  1556. sourceContent = sourceContent.replace(ser.group(0), new, 1)
  1557. elif web_source_no == '00753-14':
  1558. body = sourceContent.find("body")
  1559. body_child = body.find_all(recursive=False)
  1560. pcontent = body
  1561. if 'id' in body_child[0].attrs:
  1562. if len(body_child) <= 2 and body_child[0]['id'] == 'pcontent':
  1563. pcontent = body_child[0]
  1564. # pcontent = sourceContent.find("div", id="pcontent")
  1565. pcontent = pcontent.find_all(recursive=False)[0]
  1566. first_table = None
  1567. for idx in range(len(pcontent.find_all(recursive=False))):
  1568. t_part = pcontent.find_all(recursive=False)[idx]
  1569. if t_part.name != "table":
  1570. break
  1571. if idx == 0:
  1572. first_table = t_part
  1573. else:
  1574. for _tr in t_part.find("tbody").find_all(recursive=False):
  1575. first_table.find("tbody").append(_tr)
  1576. t_part.clear()
  1577. elif web_source_no == 'DX008357-11':
  1578. body = sourceContent.find("body")
  1579. body_child = body.find_all(recursive=False)
  1580. pcontent = body
  1581. if 'id' in body_child[0].attrs:
  1582. if len(body_child) <= 2 and body_child[0]['id'] == 'pcontent':
  1583. pcontent = body_child[0]
  1584. # pcontent = sourceContent.find("div", id="pcontent")
  1585. pcontent = pcontent.find_all(recursive=False)[0]
  1586. error_table = []
  1587. is_error_table = False
  1588. for part in pcontent.find_all(recursive=False):
  1589. if is_error_table:
  1590. if part.name == "table":
  1591. error_table.append(part)
  1592. else:
  1593. break
  1594. if part.name == "div" and part.get_text(strip=True) == "中标候选单位:":
  1595. is_error_table = True
  1596. first_table = None
  1597. for idx in range(len(error_table)):
  1598. t_part = error_table[idx]
  1599. # if t_part.name != "table":
  1600. # break
  1601. if idx == 0:
  1602. for _tr in t_part.find("tbody").find_all(recursive=False):
  1603. if _tr.get_text(strip=True) == "":
  1604. _tr.decompose()
  1605. first_table = t_part
  1606. else:
  1607. for _tr in t_part.find("tbody").find_all(recursive=False):
  1608. if _tr.get_text(strip=True) != "":
  1609. first_table.find("tbody").append(_tr)
  1610. t_part.clear()
  1611. elif web_source_no == '18021-2':
  1612. body = sourceContent.find("body")
  1613. body_child = body.find_all(recursive=False)
  1614. pcontent = body
  1615. if 'id' in body_child[0].attrs:
  1616. if len(body_child) <= 2 and body_child[0]['id'] == 'pcontent':
  1617. pcontent = body_child[0]
  1618. # pcontent = sourceContent.find("div", id="pcontent")
  1619. td = pcontent.find_all("td")
  1620. for _td in td:
  1621. if str(_td.string).strip() == "报价金额":
  1622. _td.string = "单价"
  1623. elif web_source_no == '13740-2':
  1624. # “xxx成为成交供应商”
  1625. re_match = re.search("[^,。]+成为[^,。]*成交供应商", sourceContent)
  1626. if re_match:
  1627. sourceContent = sourceContent.replace(re_match.group(), "成交人:" + re_match.group())
  1628. elif web_source_no == '03786-10':
  1629. ser1 = re.search('中标价:([\d,.]+)', sourceContent)
  1630. ser2 = re.search('合同金额[((]万元[))]:([\d,.]+)', sourceContent)
  1631. if ser1 and ser2:
  1632. m1 = ser1.group(1).replace(',', '')
  1633. m2 = ser2.group(1).replace(',', '')
  1634. if float(m1) < 100000 and (m1.split('.')[0] == m2.split('.')[0] or m2 == '0'):
  1635. new = '中标价(万元):' + m1
  1636. sourceContent = sourceContent.replace(ser1.group(0), new, 1)
  1637. elif web_source_no=='00076-4':
  1638. ser = re.search('主要标的数量:([0-9一]+)\w{,3},主要标的单价:([\d,.]+)元?,合同金额:(.00),', sourceContent)
  1639. if ser:
  1640. num = ser.group(1).replace('一', '1')
  1641. try:
  1642. num = 1 if num == '0' else num
  1643. unit_price = ser.group(2).replace(',', '')
  1644. total_price = str(int(num) * float(unit_price))
  1645. new = '合同金额:' + total_price
  1646. sourceContent = sourceContent.replace('合同金额:.00', new, 1)
  1647. except Exception as e:
  1648. log('preprocessing.py special_treatment exception')
  1649. elif web_source_no=='DX000105-2':
  1650. if re.search("成交公示", sourceContent) and re.search(',投标人:', sourceContent) and re.search(',成交人:', sourceContent)==None:
  1651. sourceContent = sourceContent.replace(',投标人:', ',成交人:')
  1652. elif web_source_no in ['04080-3', '04080-4']:
  1653. ser = re.search('合同金额:([0-9,]+.[0-9]{3,})(.{,4})', sourceContent)
  1654. if ser and '万' not in ser.group(2):
  1655. sourceContent = sourceContent.replace('合同金额:', '合同金额(万元):')
  1656. elif web_source_no=='03761-3':
  1657. ser = re.search('中标价,([0-9]+)[.0-9]*%', sourceContent)
  1658. if ser and int(ser.group(1))>100:
  1659. sourceContent = sourceContent.replace(ser.group(0), ser.group(0)[:-1]+'元')
  1660. elif web_source_no=='00695-7':
  1661. ser = re.search('支付金额:', sourceContent)
  1662. if ser:
  1663. sourceContent = sourceContent.replace('支付金额:', '合同金额:')
  1664. return sourceContent
  1665. except Exception as e:
  1666. log('特殊数据源: %s 预处理特别修改抛出异常: %s'%(web_source_no, e))
  1667. return sourceContent
  1668. def article_limit(soup,limit_words=30000):
  1669. sub_space = re.compile("\s+")
  1670. def soup_limit(_soup,_count,max_count=30000,max_gap=500):
  1671. """
  1672. :param _soup: soup
  1673. :param _count: 当前字数
  1674. :param max_count: 字数最大限制
  1675. :param max_gap: 超过限制后的最大误差
  1676. :return:
  1677. """
  1678. _gap = _count - max_count
  1679. _is_skip = False
  1680. next_soup = None
  1681. while len(_soup.find_all(recursive=False)) == 1 and \
  1682. _soup.get_text(strip=True) == _soup.find_all(recursive=False)[0].get_text(strip=True):
  1683. _soup = _soup.find_all(recursive=False)[0]
  1684. if len(_soup.find_all(recursive=False)) == 0:
  1685. _soup.string = str(_soup.get_text())[:max_count-_count]
  1686. _count += len(re.sub(sub_space, "", _soup.string))
  1687. _gap = _count - max_count
  1688. next_soup = None
  1689. else:
  1690. for _soup_part in _soup.find_all(recursive=False):
  1691. if not _is_skip:
  1692. _count += len(re.sub(sub_space, "", _soup_part.get_text()))
  1693. if _count >= max_count:
  1694. _gap = _count - max_count
  1695. if _gap <= max_gap:
  1696. _is_skip = True
  1697. else:
  1698. _is_skip = True
  1699. next_soup = _soup_part
  1700. _count -= len(re.sub(sub_space, "", _soup_part.get_text()))
  1701. continue
  1702. else:
  1703. _soup_part.decompose()
  1704. return _count,_gap,next_soup
  1705. text_count = 0
  1706. have_attachment = False
  1707. attachment_part = None
  1708. for child in soup.find_all(recursive=True):
  1709. if child.name == 'div' and 'class' in child.attrs:
  1710. if "richTextFetch" in child['class']:
  1711. child.insert_before("##attachment##。") # 句号分开,避免项目名称等提取
  1712. attachment_part = child
  1713. have_attachment = True
  1714. break
  1715. if not have_attachment:
  1716. # 无附件
  1717. if len(re.sub(sub_space, "", soup.get_text())) > limit_words:
  1718. text_count,gap,n_soup = soup_limit(soup,text_count,max_count=limit_words,max_gap=500)
  1719. while n_soup:
  1720. text_count, gap, n_soup = soup_limit(n_soup, text_count, max_count=limit_words, max_gap=500)
  1721. else:
  1722. # 有附件
  1723. _text = re.sub(sub_space, "", soup.get_text())
  1724. _text_split = _text.split("##attachment##")
  1725. if len(_text_split[0])>limit_words:
  1726. main_soup = attachment_part.parent
  1727. main_text = main_soup.find_all(recursive=False)[0]
  1728. text_count, gap, n_soup = soup_limit(main_text, text_count, max_count=limit_words, max_gap=500)
  1729. while n_soup:
  1730. text_count, gap, n_soup = soup_limit(n_soup, text_count, max_count=limit_words, max_gap=500)
  1731. if len(_text_split[1])>limit_words:
  1732. # attachment_html纯文本,无子结构
  1733. if len(attachment_part.find_all(recursive=False))==0:
  1734. attachment_part.string = str(attachment_part.get_text())[:limit_words]
  1735. else:
  1736. attachment_text_nums = 0
  1737. attachment_skip = False
  1738. for part in attachment_part.find_all(recursive=False):
  1739. if not attachment_skip:
  1740. last_attachment_text_nums = attachment_text_nums
  1741. attachment_text_nums = attachment_text_nums + len(re.sub(sub_space, "", part.get_text()))
  1742. if attachment_text_nums>=limit_words:
  1743. part.string = str(part.get_text())[:limit_words-last_attachment_text_nums]
  1744. attachment_skip = True
  1745. else:
  1746. part.decompose()
  1747. return soup
  1748. def attachment_filelink(soup):
  1749. have_attachment = False
  1750. attachment_part = None
  1751. for child in soup.find_all(recursive=True):
  1752. if child.name == 'div' and 'class' in child.attrs:
  1753. if "richTextFetch" in child['class']:
  1754. attachment_part = child
  1755. have_attachment = True
  1756. break
  1757. if not have_attachment:
  1758. return soup
  1759. else:
  1760. # 附件类型:图片、表格
  1761. attachment_type = re.compile("\.(?:png|jpg|jpeg|tif|bmp|xlsx|xls)$")
  1762. attachment_dict = dict()
  1763. for _attachment in attachment_part.find_all(recursive=False):
  1764. if _attachment.name == 'div' and 'filemd5' in _attachment.attrs:
  1765. # print('filemd5',_attachment['filemd5'])
  1766. attachment_dict[_attachment['filemd5']] = _attachment
  1767. # print(attachment_dict)
  1768. for child in soup.find_all(recursive=True):
  1769. if child.name == 'div' and 'class' in child.attrs:
  1770. if "richTextFetch" in child['class']:
  1771. break
  1772. if "filelink" in child.attrs and child['filelink'] in attachment_dict:
  1773. if re.search(attachment_type,str(child.string).strip()) or \
  1774. ('original' in child.attrs and re.search(attachment_type,str(child['original']).strip())):
  1775. # 附件插入正文标识
  1776. child.insert_before("。##attachment_begin##")
  1777. child.insert_after("。##attachment_end##")
  1778. child.replace_with(attachment_dict[child['filelink']])
  1779. # print('格式化输出',soup.prettify())
  1780. return soup
  1781. def get_preprocessed_article(articles,cost_time = dict(),useselffool=True):
  1782. '''
  1783. :param articles: 待处理的article source html
  1784. :param useselffool: 是否使用selffool
  1785. :return: list_articles
  1786. '''
  1787. list_articles = []
  1788. for article in articles:
  1789. doc_id = article[0]
  1790. sourceContent = article[1]
  1791. sourceContent = re.sub("<html>|</html>|<body>|</body>","",sourceContent)
  1792. sourceContent = sourceContent.replace('<br/>', '<br>')
  1793. sourceContent = re.sub("<br>(\s{0,}<br>)+","<br>",sourceContent)
  1794. # for br_match in re.findall("[^>]+?<br>",sourceContent):
  1795. # _new = re.sub("<br>","",br_match)
  1796. # # <br>标签替换为<p>标签
  1797. # if not re.search("^\s+$",_new):
  1798. # _new = '<p>'+_new + '</p>'
  1799. # # print(br_match,_new)
  1800. # sourceContent = sourceContent.replace(br_match,_new,1)
  1801. _send_doc_id = article[3]
  1802. _title = article[4]
  1803. page_time = article[5]
  1804. web_source_no = article[6]
  1805. '''特别数据源对 html 做特别修改'''
  1806. if web_source_no in ['DX000202-1']:
  1807. sourceContent = special_treatment(sourceContent, web_source_no)
  1808. #表格处理
  1809. key_preprocess = "tableToText"
  1810. start_time = time.time()
  1811. # article_processed = tableToText(BeautifulSoup(sourceContent,"lxml"))
  1812. article_processed = BeautifulSoup(sourceContent,"lxml")
  1813. '''特别数据源对 BeautifulSoup(html) 做特别修改'''
  1814. if web_source_no in ["00753-14","DX008357-11","18021-2"]:
  1815. article_processed = special_treatment(article_processed, web_source_no)
  1816. for _soup in article_processed.descendants:
  1817. # 识别无标签文本,添加<span>标签
  1818. if not _soup.name and not _soup.parent.string and _soup.string.strip()!="":
  1819. # print(_soup.parent.string,_soup.string.strip())
  1820. _soup.wrap(article_processed.new_tag("span"))
  1821. # print(article_processed)
  1822. # 正文和附件内容限制字数30000
  1823. article_processed = article_limit(article_processed, limit_words=30000)
  1824. # 把每个附件识别对应的html放回原来出现的位置
  1825. article_processed = attachment_filelink(article_processed)
  1826. article_processed = get_preprocessed_outline(article_processed)
  1827. # print('article_processed')
  1828. article_processed = tableToText(article_processed)
  1829. article_processed = segment(article_processed)
  1830. article_processed = article_processed.replace('(', '(').replace(')', ')') #2022/8/10 统一为中文括号
  1831. article_processed = article_processed.replace('.','.') # 2021/12/01 修正OCR识别PDF小数点错误问题
  1832. article_processed = article_processed.replace('报价限价', '招标限价') #2021/12/17 由于报价限价预测为中投标金额所以修改
  1833. article_processed = article_processed.replace('成交工程价款', '成交工程价') # 2021/12/21 修正为中标价
  1834. article_processed = re.sub('任务(?=编号[::])', '项目',article_processed) # 2022/08/10 修正为项目编号
  1835. article_processed = article_processed.replace('招标(建设)单位', '招标单位') #2022/8/10 修正预测不到表达
  1836. article_processed = re.sub('(招标|采购)人(概况|信息)[,。]', '采购人信息:', article_processed) # 2022/8/10统一表达
  1837. # 修复OCR金额中“,”、“。”识别错误
  1838. article_processed_list = article_processed.split("##attachment##")
  1839. if len(article_processed_list)>1:
  1840. attachment_text = article_processed_list[1]
  1841. for _match in re.finditer("\d。\d{2}",attachment_text):
  1842. _match_text = _match.group()
  1843. attachment_text = attachment_text.replace(_match_text,_match_text.replace("。","."),1)
  1844. for _match in re.finditer("(\d,\d{3})[,,.]",attachment_text):
  1845. _match_text = _match.group()
  1846. attachment_text = attachment_text.replace(_match_text,_match_text.replace(",",","),1)
  1847. article_processed_list[1] = attachment_text
  1848. article_processed = "##attachment##".join(article_processed_list)
  1849. '''特别数据源对 预处理后文本 做特别修改'''
  1850. if web_source_no in ['03786-10', '00076-4', 'DX000105-2', '04080-3', '04080-4', '03761-3', '00695-7',"13740-2"]:
  1851. article_processed = special_treatment(article_processed, web_source_no)
  1852. # 提取bidway
  1853. list_bidway = extract_bidway(article_processed, _title)
  1854. if list_bidway:
  1855. bidway = list_bidway[0].get("body")
  1856. # bidway名称统一规范
  1857. bidway = bidway_integrate(bidway)
  1858. else:
  1859. bidway = ""
  1860. # 修正被","逗号分隔的时间
  1861. repair_time = re.compile("[12]\d,?\d,?\d,?[-—-―/年],?[0-1]?\d,?[-—-―/月],?[0-3]?\d,?[日号]?,?(?:上午|下午)?,?[0-2]?\d,?:,?[0-6]\d,?:,?[0-6]\d|"
  1862. "[12]\d,?\d,?\d,?[-—-―/年],?[0-1]?\d,?[-—-―/月],?[0-3]?\d,?[日号]?,?(?:上午|下午)?,?[0-2]?\d,?[:时点],?[0-6]\d分?|"
  1863. "[12]\d,?\d,?\d,?[-—-―/年],?[0-1]?\d,?[-—-―/月],?[0-3]?\d,?[日号]?,?(?:上午|下午)?,?[0-2]?\d,?[时点]|"
  1864. "[12]\d,?\d,?\d,?[-—-―/年],?[0-1]?\d,?[-—-―/月],?[0-3]?\d,?[日号]|"
  1865. "[0-2]?\d,?:,?[0-6]\d,?:,?[0-6]\d"
  1866. )
  1867. for _time in set(re.findall(repair_time,article_processed)):
  1868. if re.search(",",_time):
  1869. _time2 = re.sub(",", "", _time)
  1870. item = re.search("[12]\d{3}[-—-―/][0-1]?\d[-—-―/][0-3]\d(?=\d)", _time2)
  1871. if item:
  1872. _time2 = _time2.replace(item.group(),item.group() + " ")
  1873. article_processed = article_processed.replace(_time, _time2)
  1874. else:
  1875. item = re.search("[12]\d{3}[-—-―/][0-1]?\d[-—-―/][0-3]\d(?=\d)", _time)
  1876. if item:
  1877. _time2 = _time.replace(item.group(),item.group() + " ")
  1878. article_processed = article_processed.replace(_time, _time2)
  1879. # print('re_rtime',re.findall(repair_time,article_processed))
  1880. # log(article_processed)
  1881. if key_preprocess not in cost_time:
  1882. cost_time[key_preprocess] = 0
  1883. cost_time[key_preprocess] += round(time.time()-start_time,2)
  1884. #article_processed = article[1]
  1885. _article = Article(doc_id,article_processed,sourceContent,_send_doc_id,_title,
  1886. bidway=bidway)
  1887. _article.fingerprint = getFingerprint(_title+sourceContent)
  1888. _article.page_time = page_time
  1889. list_articles.append(_article)
  1890. return list_articles
  1891. def get_preprocessed_sentences(list_articles,useselffool=True,cost_time=dict()):
  1892. '''
  1893. :param list_articles: 经过预处理的article text
  1894. :return: list_sentences
  1895. '''
  1896. list_sentences = []
  1897. list_outlines = []
  1898. for article in list_articles:
  1899. list_sentences_temp = []
  1900. list_entitys_temp = []
  1901. doc_id = article.id
  1902. _send_doc_id = article.doc_id
  1903. _title = article.title
  1904. #表格处理
  1905. key_preprocess = "tableToText"
  1906. start_time = time.time()
  1907. article_processed = article.content
  1908. if len(_title)<100 and _title not in article_processed: # 把标题放到正文
  1909. article_processed = _title + article_processed
  1910. attachment_begin_index = -1
  1911. if key_preprocess not in cost_time:
  1912. cost_time[key_preprocess] = 0
  1913. cost_time[key_preprocess] += time.time()-start_time
  1914. #nlp处理
  1915. if article_processed is not None and len(article_processed)!=0:
  1916. split_patten = "。"
  1917. sentences = []
  1918. _begin = 0
  1919. sentences_set = set()
  1920. for _iter in re.finditer(split_patten,article_processed):
  1921. _sen = article_processed[_begin:_iter.span()[1]]
  1922. if len(_sen)>0 and _sen not in sentences_set:
  1923. # 标识在附件里的句子
  1924. if re.search("##attachment##",_sen):
  1925. attachment_begin_index = len(sentences)
  1926. # _sen = re.sub("##attachment##","",_sen)
  1927. sentences.append(_sen)
  1928. sentences_set.add(_sen)
  1929. _begin = _iter.span()[1]
  1930. _sen = article_processed[_begin:]
  1931. if re.search("##attachment##", _sen):
  1932. # _sen = re.sub("##attachment##", "", _sen)
  1933. attachment_begin_index = len(sentences)
  1934. if len(_sen)>0 and _sen not in sentences_set:
  1935. sentences.append(_sen)
  1936. sentences_set.add(_sen)
  1937. # 解析outline大纲分段
  1938. outline_list = []
  1939. if re.search("##split##",article.content):
  1940. temp_sentences = []
  1941. last_sentence_index = (-1,-1)
  1942. outline_index = 0
  1943. for sentence_index in range(len(sentences)):
  1944. sentence_text = sentences[sentence_index]
  1945. for _ in re.findall("##split##", sentence_text):
  1946. _match = re.search("##split##", sentence_text)
  1947. if last_sentence_index[0] > -1:
  1948. sentence_begin_index,wordOffset_begin = last_sentence_index
  1949. sentence_end_index = sentence_index
  1950. wordOffset_end = _match.start()
  1951. if sentence_begin_index<attachment_begin_index and sentence_end_index>=attachment_begin_index:
  1952. outline_list.append(Outline(doc_id,outline_index,'',sentence_begin_index,attachment_begin_index-1,wordOffset_begin,len(sentences[attachment_begin_index-1])))
  1953. else:
  1954. outline_list.append(Outline(doc_id,outline_index,'',sentence_begin_index,sentence_end_index,wordOffset_begin,wordOffset_end))
  1955. outline_index += 1
  1956. sentence_text = re.sub("##split##", "", sentence_text,count=1)
  1957. last_sentence_index = (sentence_index,_match.start())
  1958. temp_sentences.append(sentence_text)
  1959. if attachment_begin_index>-1 and last_sentence_index[0]<attachment_begin_index:
  1960. 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])))
  1961. else:
  1962. outline_list.append(Outline(doc_id,outline_index,'',last_sentence_index[0],len(sentences)-1,last_sentence_index[1],len(temp_sentences[-1])))
  1963. sentences = temp_sentences
  1964. #解析outline的outline_text内容
  1965. for _outline in outline_list:
  1966. if _outline.sentence_begin_index==_outline.sentence_end_index:
  1967. _text = sentences[_outline.sentence_begin_index][_outline.wordOffset_begin:_outline.wordOffset_end]
  1968. else:
  1969. _text = ""
  1970. for idx in range(_outline.sentence_begin_index,_outline.sentence_end_index+1):
  1971. if idx==_outline.sentence_begin_index:
  1972. _text += sentences[idx][_outline.wordOffset_begin:]
  1973. elif idx==_outline.sentence_end_index:
  1974. _text += sentences[idx][:_outline.wordOffset_end]
  1975. else:
  1976. _text += sentences[idx]
  1977. _outline.outline_text = _text
  1978. _outline_summary = re.split("[::,]",_text,1)[0]
  1979. if len(_outline_summary)<20:
  1980. _outline.outline_summary = _outline_summary
  1981. # print(_outline.outline_index,_outline.outline_text)
  1982. article.content = "".join(sentences)
  1983. # sentences.append(article_processed[_begin:])
  1984. lemmas = []
  1985. doc_offsets = []
  1986. dep_types = []
  1987. dep_tokens = []
  1988. time1 = time.time()
  1989. '''
  1990. tokens_all = fool.cut(sentences)
  1991. #pos_all = fool.LEXICAL_ANALYSER.pos(tokens_all)
  1992. #ner_tag_all = fool.LEXICAL_ANALYSER.ner_labels(sentences,tokens_all)
  1993. ner_entitys_all = fool.ner(sentences)
  1994. '''
  1995. #限流执行
  1996. key_nerToken = "nerToken"
  1997. start_time = time.time()
  1998. # tokens_all = getTokens(sentences,useselffool=useselffool)
  1999. tokens_all = getTokens([re.sub("##attachment_begin##|##attachment_end##","",_sen) for _sen in sentences],useselffool=useselffool)
  2000. if key_nerToken not in cost_time:
  2001. cost_time[key_nerToken] = 0
  2002. cost_time[key_nerToken] += round(time.time()-start_time,2)
  2003. in_attachment = False
  2004. for sentence_index in range(len(sentences)):
  2005. sentence_text = sentences[sentence_index]
  2006. if re.search("##attachment_begin##",sentence_text):
  2007. in_attachment = True
  2008. sentence_text = re.sub("##attachment_begin##","",sentence_text)
  2009. elif re.search("##attachment_end##",sentence_text):
  2010. in_attachment = False
  2011. sentence_text = re.sub("##attachment_end##", "", sentence_text)
  2012. if sentence_index >= attachment_begin_index and attachment_begin_index!=-1:
  2013. in_attachment = True
  2014. tokens = tokens_all[sentence_index]
  2015. #pos_tag = pos_all[sentence_index]
  2016. pos_tag = ""
  2017. ner_entitys = ""
  2018. 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))
  2019. if len(list_sentences_temp)==0:
  2020. list_sentences_temp.append(Sentences(doc_id=doc_id,sentence_index=0,sentence_text="sentence_text",tokens=[],pos_tags=[],ner_tags=""))
  2021. list_sentences.append(list_sentences_temp)
  2022. list_outlines.append(outline_list)
  2023. return list_sentences,list_outlines
  2024. def get_preprocessed_entitys(list_sentences,useselffool=True,cost_time=dict()):
  2025. '''
  2026. :param list_sentences:分局情况
  2027. :param cost_time:
  2028. :return: list_entitys
  2029. '''
  2030. list_entitys = []
  2031. for list_sentence in list_sentences:
  2032. sentences = []
  2033. list_entitys_temp = []
  2034. for _sentence in list_sentence:
  2035. sentences.append(_sentence.sentence_text)
  2036. lemmas = []
  2037. doc_offsets = []
  2038. dep_types = []
  2039. dep_tokens = []
  2040. time1 = time.time()
  2041. '''
  2042. tokens_all = fool.cut(sentences)
  2043. #pos_all = fool.LEXICAL_ANALYSER.pos(tokens_all)
  2044. #ner_tag_all = fool.LEXICAL_ANALYSER.ner_labels(sentences,tokens_all)
  2045. ner_entitys_all = fool.ner(sentences)
  2046. '''
  2047. #限流执行
  2048. key_nerToken = "nerToken"
  2049. start_time = time.time()
  2050. found_yeji = 0 # 2021/8/6 增加判断是否正文包含评标结果 及类似业绩判断用于过滤后面的金额
  2051. # found_pingbiao = False
  2052. ner_entitys_all = getNers(sentences,useselffool=useselffool)
  2053. if key_nerToken not in cost_time:
  2054. cost_time[key_nerToken] = 0
  2055. cost_time[key_nerToken] += round(time.time()-start_time,2)
  2056. company_dict = set()
  2057. company_index = dict((i,set()) for i in range(len(list_sentence)))
  2058. for sentence_index in range(len(list_sentence)):
  2059. list_sentence_entitys = []
  2060. sentence_text = list_sentence[sentence_index].sentence_text
  2061. tokens = list_sentence[sentence_index].tokens
  2062. doc_id = list_sentence[sentence_index].doc_id
  2063. in_attachment = list_sentence[sentence_index].in_attachment
  2064. list_tokenbegin = []
  2065. begin = 0
  2066. for i in range(0,len(tokens)):
  2067. list_tokenbegin.append(begin)
  2068. begin += len(str(tokens[i]))
  2069. list_tokenbegin.append(begin+1)
  2070. #pos_tag = pos_all[sentence_index]
  2071. pos_tag = ""
  2072. ner_entitys = ner_entitys_all[sentence_index]
  2073. '''正则识别角色实体 经营部|经销部|电脑部|服务部|复印部|印刷部|彩印部|装饰部|修理部|汽修部|修理店|零售店|设计店|服务店|家具店|专卖店|分店|文具行|商行|印刷厂|修理厂|维修中心|修配中心|养护中心|服务中心|会馆|文化馆|超市|门市|商场|家具城|印刷社|经销处'''
  2074. for it in re.finditer(
  2075. '(?P<text_key_word>(((单一来源|中标|中选|中价|成交)(供应商|供货商|服务商|候选人|单位|人))|(供应商|供货商|服务商|候选人))(名称)?[为::]+)(?P<text>([^,。、;《::]{5,20})(厂|中心|超市|门市|商场|工作室|文印室|城|部|店|站|馆|行|社|处))[,。]',
  2076. sentence_text):
  2077. for k, v in it.groupdict().items():
  2078. if k == 'text_key_word':
  2079. keyword = v
  2080. if k == 'text':
  2081. entity = v
  2082. b = it.start() + len(keyword)
  2083. e = it.end() - 1
  2084. if (b, e, 'location', entity) in ner_entitys:
  2085. ner_entitys.remove((b, e, 'location', entity))
  2086. ner_entitys.append((b, e, 'company', entity))
  2087. elif (b, e, 'org', entity) not in ner_entitys and (b, e, 'company', entity) not in ner_entitys:
  2088. ner_entitys.append((b, e, 'company', entity))
  2089. for it in re.finditer(
  2090. '(?P<text_key_word>((建设|招租|招标|采购)(单位|人)|业主)(名称)?[为::]+)(?P<text>\w{2,4}[省市县区镇]([^,。、;《]{2,20})(管理处|办公室|委员会|村委会|纪念馆|监狱|管教所|修养所|社区|农场|林场|羊场|猪场|石场|村|幼儿园))[,。]',
  2091. sentence_text):
  2092. for k, v in it.groupdict().items():
  2093. if k == 'text_key_word':
  2094. keyword = v
  2095. if k == 'text':
  2096. entity = v
  2097. b = it.start() + len(keyword)
  2098. e = it.end() - 1
  2099. if (b, e, 'location', entity) in ner_entitys:
  2100. ner_entitys.remove((b, e, 'location', entity))
  2101. ner_entitys.append((b, e, 'org', entity))
  2102. if (b, e, 'org', entity) not in ner_entitys and (b, e, 'company', entity) not in ner_entitys:
  2103. ner_entitys.append((b, e, 'org', entity))
  2104. for ner_entity in ner_entitys:
  2105. if ner_entity[2] in ['company','org']:
  2106. company_dict.add((ner_entity[2],ner_entity[3]))
  2107. company_index[sentence_index].add((ner_entity[0],ner_entity[1]))
  2108. #识别package
  2109. #识别实体
  2110. for ner_entity in ner_entitys:
  2111. begin_index_temp = ner_entity[0]
  2112. end_index_temp = ner_entity[1]
  2113. entity_type = ner_entity[2]
  2114. entity_text = ner_entity[3]
  2115. if entity_type in ["org","company"] and not isLegalEnterprise(entity_text):
  2116. continue
  2117. for j in range(len(list_tokenbegin)):
  2118. if list_tokenbegin[j]==begin_index_temp:
  2119. begin_index = j
  2120. break
  2121. elif list_tokenbegin[j]>begin_index_temp:
  2122. begin_index = j-1
  2123. break
  2124. begin_index_temp += len(str(entity_text))
  2125. for j in range(begin_index,len(list_tokenbegin)):
  2126. if list_tokenbegin[j]>=begin_index_temp:
  2127. end_index = j-1
  2128. break
  2129. entity_id = "%s_%d_%d_%d"%(doc_id,sentence_index,begin_index,end_index)
  2130. #去掉标点符号
  2131. entity_text = re.sub("[,,。:!&@$\*]","",entity_text)
  2132. entity_text = entity_text.replace("(","(").replace(")",")") if isinstance(entity_text,str) else entity_text
  2133. 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))
  2134. # 标记文章末尾的"发布人”、“发布时间”实体
  2135. if sentence_index==len(list_sentence)-1:
  2136. if len(list_sentence_entitys[-2:])>2:
  2137. second2last = list_sentence_entitys[-2]
  2138. last = list_sentence_entitys[-1]
  2139. if (second2last.entity_type in ["company",'org'] and last.entity_type=="time") or (
  2140. second2last.entity_type=="time" and last.entity_type in ["company",'org']):
  2141. if last.wordOffset_begin - second2last.wordOffset_end < 6 and len(sentence_text) - last.wordOffset_end<6:
  2142. last.is_tail = True
  2143. second2last.is_tail = True
  2144. #使用正则识别金额
  2145. entity_type = "money"
  2146. #money_patten_str = "(([1-9][\d,,]*(?:\.\d+)?[百千万亿]?[\(\)()元整]+)|([零壹贰叁肆伍陆柒捌玖拾佰仟萬億十百千万亿元角分]{3,})|(?:[¥¥]+,?|报价|标价)[(\(]?([万])?元?[)\)]?[::]?.{,7}?([1-9][\d,,]*(?:\.\d+)?(?:,?)[百千万亿]?)|([1-9][\d,,]*(?:\.\d+)?(?:,?)[百千万亿]?)[\((]?([万元]{1,2}))*"
  2147. # list_money_pattern = {"cn":"(()()(?P<money_cn>[零壹贰叁肆伍陆柒捌玖拾佰仟萬億圆十百千万亿元角分]{3,})())",
  2148. # "key_word":"((?P<text_key_word>(?:[¥¥]+,?|[单报标限]价|金额|价格|标的基本情况|CNY|成交结果:)(?:[,(\(]*\s*(?P<unit_key_word_before>[万元]*(?P<filter_unit2>[台个只]*))\s*[)\)]?)\s*[,,::]*(\s*[^壹贰叁肆伍陆柒捌玖拾佰仟萬億分万元]{,8}?))(?P<money_key_word>[0-9][\d,]*(?:\.\d+)?(?:,?)[百千万亿元]*)(?:[(\(]?(?P<filter_>[%])*\s*(?P<unit_key_word_behind>[万元]*(?P<filter_unit1>[台个只]*))\s*[)\)]?))",
  2149. # "front_m":"((?P<text_front_m>(?:[(\(]?\s*(?P<unit_front_m_before>[万元]+)\s*[)\)])\s*[,,::]*(\s*[^壹贰叁肆伍陆柒捌玖拾佰仟萬億分万元]{,7}?))(?P<money_front_m>[0-9][\d,]*(?:\.\d+)?(?:,?)[百千万亿元]*)())",
  2150. # "behind_m":"(()()(?P<money_behind_m>[0-9][\d,,]*(?:\.\d+)?(?:,?)[百千万亿]*)[\((]?(?P<unit_behind_m>[万元]+(?P<filter_unit3>[台个只]*))[\))]?)"}
  2151. list_money_pattern = {"cn":"(()()(?P<money_cn>[零壹贰叁肆伍陆柒捌玖拾佰仟萬億圆十百千万亿元角分]{3,})())",
  2152. "key_word": "((?P<text_key_word>(?:[¥¥]+,?|[单报标限总]价|金额|成交报?价|价格|预算(金额)?|(监理|设计|勘察)(服务)?费|标的基本情况|CNY|成交结果|成交额|中标额)(?:[,,(\(]*\s*(人民币)?(?P<unit_key_word_before>[万亿]?元?(?P<filter_unit2>[台个只吨]*))\s*(/?费率)?(人民币)?[)\)]?)\s*[,,::]*(\s*[^壹贰叁肆伍陆柒捌玖拾佰仟萬億分万元编号时间]{,8}?))(第[123一二三]名[::])?(\d+(\*\d+%)+=)?(?P<money_key_word>[0-9][\d,]*(?:\.\d+)?(?:,?)[百千]{,1})(?:[(\(]?(?P<filter_>[%])*\s*(单位[::])?(?P<unit_key_word_behind>[万亿]?元?(?P<filter_unit1>[台只吨斤棵株页亩方条天]*))\s*[)\)]?))",
  2153. "front_m":"((?P<text_front_m>(?:[(\(]?\s*(?P<unit_front_m_before>[万亿]?元)\s*[)\)])\s*[,,::]*(\s*[^壹贰叁肆伍陆柒捌玖拾佰仟萬億分万元]{,7}?))(?P<money_front_m>[0-9][\d,]*(?:\.\d+)?(?:,?)[百千]*)())",
  2154. "behind_m":"(()()(?P<money_behind_m>[0-9][\d,]*(?:\.\d+)?(?:,?)[百千]*)(人民币)?[\((]?(?P<unit_behind_m>[万亿]?元(?P<filter_unit3>[台个只吨斤棵株页亩方条米]*))[\))]?)"}
  2155. # 2021/7/19 调整金额,单位提取正则,修复部分金额因为单位提取失败被过滤问题。
  2156. pattern_money = re.compile("%s|%s|%s|%s"%(list_money_pattern["cn"],list_money_pattern["key_word"],list_money_pattern["behind_m"],list_money_pattern["front_m"]))
  2157. set_begin = set()
  2158. # for pattern_key in list_money_pattern.keys():
  2159. # for pattern_key in ["cn","key_word","behind_m","front_m"]:
  2160. # # pattern = re.compile(list_money_pattern[pattern_key])
  2161. # pattern = re.compile("(()()([零壹贰叁肆伍陆柒捌玖拾佰仟萬億十百千万亿元角分]{3,})())*|((?:[¥¥]+,?|[报标限]价|金额)(?:[(\(]?\s*([万元]*)\s*[)\)]?)\s*[::]?(\s*[^壹贰叁肆伍陆柒捌玖拾佰仟萬億分]{,7}?)([0-9][\d,,]*(?:\.\d+)?(?:,?)[百千万亿元]*)(?:[(\(]?\s*([万元]*)\s*[)\)]?))*|(()()([0-9][\d,,]*(?:\.\d+)?(?:,?)[百千万亿]*)[\((]?([万元]+)[\))]?)*|((?:[(\(]?\s*([万元]+)\s*[)\)])\s*[::]?(\s*[^壹贰叁肆伍陆柒捌玖拾佰仟萬億分]{,7}?)([0-9][\d,,]*(?:\.\d+)?(?:,?)[百千万亿元]*)())*")
  2162. # all_match = re.findall(pattern, sentence_text)
  2163. # index = 0
  2164. # for i in range(len(all_match)):
  2165. # if len(all_match[i][0])>0:
  2166. # print("===",all_match[i])
  2167. # #print(all_match[i][0])
  2168. # unit = ""
  2169. # entity_text = all_match[i][3]
  2170. # if pattern_key in ["key_word","front_m"]:
  2171. # unit = all_match[i][1]
  2172. # if pattern_key=="key_word":
  2173. # if all_match[i][1]=="" and all_match[i][4]!="":
  2174. # unit = all_match[i][4]
  2175. # else:
  2176. # unit = all_match[i][4]
  2177. # if entity_text.find("元")>=0:
  2178. # unit = ""
  2179. #
  2180. # index += len(all_match[i][0])-len(entity_text)-len(all_match[i][4])#-len(all_match[i][1])-len(all_match[i][2])#整个提出来的作为实体->数字部分作为整体,否则会丢失特征
  2181. # begin_index_temp = index
  2182. # for j in range(len(list_tokenbegin)):
  2183. # if list_tokenbegin[j]==index:
  2184. # begin_index = j
  2185. # break
  2186. # elif list_tokenbegin[j]>index:
  2187. # begin_index = j-1
  2188. # break
  2189. # index += len(str(entity_text))+len(all_match[i][4])#+len(all_match[i][2])+len(all_match[i][1])#整个提出来的作为实体
  2190. # end_index_temp = index
  2191. # #index += len(str(all_match[i][0]))
  2192. # for j in range(begin_index,len(list_tokenbegin)):
  2193. # if list_tokenbegin[j]>=index:
  2194. # end_index = j-1
  2195. # break
  2196. # entity_id = "%s_%d_%d_%d"%(doc_id,sentence_index,begin_index,end_index)
  2197. #
  2198. # entity_text = re.sub("[^0-9.零壹贰叁肆伍陆柒捌玖拾佰仟萬億十百千万亿元角分]","",entity_text)
  2199. # if len(unit)>0:
  2200. # entity_text = str(getUnifyMoney(entity_text)*getMultipleFactor(unit[0]))
  2201. # else:
  2202. # entity_text = str(getUnifyMoney(entity_text))
  2203. #
  2204. # _exists = False
  2205. # for item in list_sentence_entitys:
  2206. # if item.entity_id==entity_id and item.entity_type==entity_type:
  2207. # _exists = True
  2208. # if not _exists:
  2209. # if float(entity_text)>1:
  2210. # 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))
  2211. #
  2212. # else:
  2213. # index += 1
  2214. # if re.search('评标结果|候选人公示', sentence_text):
  2215. # found_pingbiao = True
  2216. if re.search('业绩', sentence_text):
  2217. found_yeji += 1
  2218. if found_yeji >= 2: # 过滤掉业绩后面的所有金额
  2219. all_match = []
  2220. else:
  2221. all_match = re.finditer(pattern_money, sentence_text)
  2222. index = 0
  2223. for _match in all_match:
  2224. if len(_match.group())>0:
  2225. # print("===",_match.group())
  2226. # # print(_match.groupdict())
  2227. notes = '' # 2021/7/20 新增备注金额大写或金额单位 if 金额大写 notes=大写 elif 单位 notes=单位
  2228. unit = ""
  2229. entity_text = ""
  2230. text_beforeMoney = ""
  2231. filter = ""
  2232. filter_unit = False
  2233. notSure = False
  2234. if re.search('业绩', sentence_text[:_match.span()[0]]): # 2021/7/21过滤掉业绩后面金额
  2235. # print('金额在业绩后面: ', _match.group(0))
  2236. found_yeji += 1
  2237. break
  2238. for k,v in _match.groupdict().items():
  2239. if v!="" and v is not None:
  2240. if k=='text_key_word':
  2241. notSure = True
  2242. if k.split("_")[0]=="money":
  2243. entity_text = v
  2244. if k.split("_")[0]=="unit":
  2245. if v=='万元' or unit=="": # 处理 预算金额(元):160万元 这种出现前后单位不一致情况
  2246. unit = v
  2247. if k.split("_")[0]=="text":
  2248. text_beforeMoney = v
  2249. if k.split("_")[0]=="filter":
  2250. filter = v
  2251. if re.search("filter_unit",k) is not None:
  2252. filter_unit = True
  2253. # print(_match.group())
  2254. # print(entity_text,unit,text_beforeMoney,filter,filter_unit)
  2255. if re.search('(^\d{2,},\d{4,}万?$)|(^\d{2,},\d{2}万?$)', entity_text.strip()): # 2021/7/19 修正OCR识别小数点为逗号
  2256. if re.search('[幢栋号楼层]', sentence_text[max(0, _match.span()[0]-2):_match.span()[0]]):
  2257. entity_text = re.sub('\d+,', '', entity_text)
  2258. else:
  2259. entity_text = entity_text.replace(',', '.')
  2260. # print(' 修正OCR识别小数点为逗号')
  2261. if entity_text.find("元")>=0:
  2262. unit = ""
  2263. if unit == "": #2021/7/21 有明显金额特征的补充单位,避免被过滤
  2264. if ('¥' in text_beforeMoney or '¥' in text_beforeMoney):
  2265. unit = '元'
  2266. # print('明显金额特征补充单位 元')
  2267. elif re.search('[单报标限]价|金额|价格|(监理|设计|勘察)(服务)?费[::为]+$', text_beforeMoney.strip()) and \
  2268. re.search('\d{5,}',entity_text) and re.search('^0|1[3|4|5|6|7|8|9]\d{9}',entity_text)==None:
  2269. unit = '元'
  2270. # print('明显金额特征补充单位 元')
  2271. elif re.search('(^\d{,3}(,?\d{3})+(\.\d{2,7},?)$)|(^\d{,3}(,\d{3})+,?$)',entity_text):
  2272. unit = '元'
  2273. # print('明显金额特征补充单位 元')
  2274. if unit.find("万") >= 0 and entity_text.find("万") >= 0: #2021/7/19修改为金额文本有万,不计算单位
  2275. # print('修正金额及单位都有万, 金额:',entity_text, '单位:',unit)
  2276. unit = "元"
  2277. if re.search('.*万元万元', entity_text): #2021/7/19 修正两个万元
  2278. # print(' 修正两个万元',entity_text)
  2279. entity_text = entity_text.replace('万元万元','万元')
  2280. else:
  2281. if filter_unit:
  2282. continue
  2283. if filter!="":
  2284. continue
  2285. index = _match.span()[0]+len(text_beforeMoney)
  2286. begin_index_temp = index
  2287. for j in range(len(list_tokenbegin)):
  2288. if list_tokenbegin[j]==index:
  2289. begin_index = j
  2290. break
  2291. elif list_tokenbegin[j]>index:
  2292. begin_index = j-1
  2293. break
  2294. index = _match.span()[1]
  2295. end_index_temp = index
  2296. #index += len(str(all_match[i][0]))
  2297. for j in range(begin_index,len(list_tokenbegin)):
  2298. if list_tokenbegin[j]>=index:
  2299. end_index = j-1
  2300. break
  2301. entity_id = "%s_%d_%d_%d"%(doc_id,sentence_index,begin_index,end_index)
  2302. entity_text = re.sub("[^0-9.零壹贰叁肆伍陆柒捌玖拾佰仟萬億圆十百千万亿元角分]","",entity_text)
  2303. # print('转换前金额:', entity_text, '单位:', unit, '备注:',notes, 'text_beforeMoney:',text_beforeMoney)
  2304. if re.search('总投资|投资总额|总预算|总概算|投资规模', sentence_text[max(0, _match.span()[0] - 8):_match.span()[1]]): # 2021/8/5过滤掉总投资金额
  2305. # print('总投资金额: ', _match.group(0))
  2306. notes = '总投资'
  2307. elif re.search('投资', sentence_text[max(0, _match.span()[0] - 8):_match.span()[1]]): # 2021/11/18 投资金额不作为招标金额
  2308. notes = '投资'
  2309. elif re.search('工程造价', sentence_text[max(0, _match.span()[0] - 8):_match.span()[1]]): # 2021/12/20 工程造价不作为招标金额
  2310. notes = '工程造价'
  2311. elif (re.search('保证金', sentence_text[max(0, _match.span()[0] - 5):_match.span()[1]])
  2312. or re.search('保证金的?(缴纳)?(金额|金\?|额|\?)?[\((]*(万?元|为?人民币|大写|调整|变更|已?修改|更改|更正)?[\))]*[::为]',
  2313. sentence_text[max(0, _match.span()[0] - 10):_match.span()[1]])
  2314. or re.search('保证金由[\d.,]+.{,3}(变更|修改|更改|更正|调整?)为',
  2315. sentence_text[max(0, _match.span()[0] - 15):_match.span()[1]])):
  2316. notes = '保证金'
  2317. # print('保证金信息:', sentence_text[max(0, _match.span()[0] - 15):_match.span()[1]])
  2318. elif re.search('成本(警戒|预警)(线|价|值)[^0-9元]{,10}',
  2319. sentence_text[max(0, _match.span()[0] - 10):_match.span()[0]]):
  2320. notes = '成本警戒线'
  2321. elif re.search('(监理|设计|勘察)(服务)?费(报价)?[约为:]', sentence_text[_match.span()[0]:_match.span()[1]]):
  2322. cost_re = re.search('(监理|设计|勘察)(服务)?费', sentence_text[_match.span()[0]:_match.span()[1]])
  2323. notes = cost_re.group(1)
  2324. elif re.search('单价|总金额', sentence_text[_match.span()[0]:_match.span()[1]]):
  2325. notes = '单价'
  2326. elif re.search('[零壹贰叁肆伍陆柒捌玖拾佰仟萬億圆]', entity_text) != None:
  2327. notes = '大写'
  2328. if entity_text[0] == "拾": # 2021/12/16 修正大写金额省略了数字转换错误问题
  2329. entity_text = "壹"+entity_text
  2330. # print("补充备注:notes = 大写")
  2331. if len(unit)>0:
  2332. if unit.find('万')>=0 and len(entity_text.split('.')[0])>=8: # 2021/7/19 修正万元金额过大的情况
  2333. # print('修正单位万元金额过大的情况 金额:', entity_text, '单位:', unit)
  2334. entity_text = str(getUnifyMoney(entity_text) * getMultipleFactor(unit[0])/10000)
  2335. unit = '元' # 修正金额后单位 重置为元
  2336. else:
  2337. # print('str(getUnifyMoney(entity_text)*getMultipleFactor(unit[0])):')
  2338. entity_text = str(getUnifyMoney(entity_text)*getMultipleFactor(unit[0]))
  2339. else:
  2340. if entity_text.find('万')>=0 and entity_text.split('.')[0].isdigit() and len(entity_text.split('.')[0])>=8:
  2341. entity_text = str(getUnifyMoney(entity_text)/10000)
  2342. # print('修正金额字段含万 过大的情况')
  2343. else:
  2344. entity_text = str(getUnifyMoney(entity_text))
  2345. if float(entity_text)>100000000000 or float(entity_text)<100: # float(entity_text)<100 or 2022/3/4 取消最小金额限制
  2346. # print('过滤掉金额:float(entity_text)<100 or float(entity_text)>100000000000', entity_text, unit)
  2347. continue
  2348. if notSure and unit=="" and float(entity_text)>100*10000:
  2349. # print('过滤掉金额 notSure and unit=="" and float(entity_text)>100*10000:', entity_text, unit)
  2350. continue
  2351. _exists = False
  2352. for item in list_sentence_entitys:
  2353. if item.entity_id==entity_id and item.entity_type==entity_type:
  2354. _exists = True
  2355. if (begin_index >=item.begin_index and begin_index<=item.end_index) or (end_index>=item.begin_index and end_index<=item.end_index):
  2356. _exists = True
  2357. if not _exists:
  2358. if float(entity_text)>1:
  2359. 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,in_attachment=in_attachment))
  2360. list_sentence_entitys[-1].notes = notes # 2021/7/20 新增金额备注
  2361. list_sentence_entitys[-1].money_unit = unit # 2021/7/20 新增金额备注
  2362. # print('预处理中的 金额:%s, 单位:%s'%(entity_text,unit))
  2363. # print(entity_text,unit,notes)
  2364. else:
  2365. index += 1
  2366. # "联系人"正则补充提取 2021/11/15 新增
  2367. list_person_text = [entity.entity_text for entity in list_sentence_entitys if entity.entity_type=='person']
  2368. error_text = ['交易','机构','教育','项目','公司','中标','开标','截标','监督','政府','国家','中国','技术','投标','传真','网址','电子邮',
  2369. '联系','联系电','联系地','采购代','邮政编','邮政','电话','手机','手机号','联系人','地址','地点','邮箱','邮编','联系方','招标','招标人','代理',
  2370. '代理人','采购','附件','注意','登录','报名','踏勘',"测试"]
  2371. list_person_text = set(list_person_text + error_text)
  2372. re_person = re.compile("联系人[::]([\u4e00-\u9fa5]工)|"
  2373. "联系人[::]([\u4e00-\u9fa5]{2,3})(?=联系)|"
  2374. "联系人[::]([\u4e00-\u9fa5]{2,3})")
  2375. list_person = []
  2376. if not in_attachment:
  2377. for match_result in re_person.finditer(sentence_text):
  2378. match_text = match_result.group()
  2379. entity_text = match_text[4:]
  2380. wordOffset_begin = match_result.start() + 4
  2381. wordOffset_end = match_result.end()
  2382. # print(text[wordOffset_begin:wordOffset_end])
  2383. # 排除一些不为人名的实体
  2384. if re.search("^[\u4e00-\u9fa5]{7,}([,。]|$)",sentence_text[wordOffset_begin:wordOffset_begin+20]):
  2385. continue
  2386. if entity_text not in list_person_text and entity_text[:2] not in list_person_text:
  2387. _person = dict()
  2388. _person['body'] = entity_text
  2389. _person['begin_index'] = wordOffset_begin
  2390. _person['end_index'] = wordOffset_end
  2391. list_person.append(_person)
  2392. entity_type = "person"
  2393. for person in list_person:
  2394. begin_index_temp = person['begin_index']
  2395. for j in range(len(list_tokenbegin)):
  2396. if list_tokenbegin[j] == begin_index_temp:
  2397. begin_index = j
  2398. break
  2399. elif list_tokenbegin[j] > begin_index_temp:
  2400. begin_index = j - 1
  2401. break
  2402. index = person['end_index']
  2403. end_index_temp = index
  2404. for j in range(begin_index, len(list_tokenbegin)):
  2405. if list_tokenbegin[j] >= index:
  2406. end_index = j - 1
  2407. break
  2408. entity_id = "%s_%d_%d_%d" % (doc_id, sentence_index, begin_index, end_index)
  2409. entity_text = person['body']
  2410. list_sentence_entitys.append(
  2411. Entity(doc_id, entity_id, entity_text, entity_type, sentence_index, begin_index, end_index,
  2412. begin_index_temp, end_index_temp,in_attachment=in_attachment))
  2413. # 资金来源提取 2020/12/30 新增
  2414. list_moneySource = extract_moneySource(sentence_text)
  2415. entity_type = "moneysource"
  2416. for moneySource in list_moneySource:
  2417. begin_index_temp = moneySource['begin_index']
  2418. for j in range(len(list_tokenbegin)):
  2419. if list_tokenbegin[j] == begin_index_temp:
  2420. begin_index = j
  2421. break
  2422. elif list_tokenbegin[j] > begin_index_temp:
  2423. begin_index = j - 1
  2424. break
  2425. index = moneySource['end_index']
  2426. end_index_temp = index
  2427. for j in range(begin_index, len(list_tokenbegin)):
  2428. if list_tokenbegin[j] >= index:
  2429. end_index = j - 1
  2430. break
  2431. entity_id = "%s_%d_%d_%d" % (doc_id, sentence_index, begin_index, end_index)
  2432. entity_text = moneySource['body']
  2433. list_sentence_entitys.append(
  2434. Entity(doc_id, entity_id, entity_text, entity_type, sentence_index, begin_index, end_index,
  2435. begin_index_temp, end_index_temp,in_attachment=in_attachment))
  2436. # 电子邮箱提取 2021/11/04 新增
  2437. list_email = extract_email(sentence_text)
  2438. entity_type = "email" # 电子邮箱
  2439. for email in list_email:
  2440. begin_index_temp = email['begin_index']
  2441. for j in range(len(list_tokenbegin)):
  2442. if list_tokenbegin[j] == begin_index_temp:
  2443. begin_index = j
  2444. break
  2445. elif list_tokenbegin[j] > begin_index_temp:
  2446. begin_index = j - 1
  2447. break
  2448. index = email['end_index']
  2449. end_index_temp = index
  2450. for j in range(begin_index, len(list_tokenbegin)):
  2451. if list_tokenbegin[j] >= index:
  2452. end_index = j - 1
  2453. break
  2454. entity_id = "%s_%d_%d_%d" % (doc_id, sentence_index, begin_index, end_index)
  2455. entity_text = email['body']
  2456. list_sentence_entitys.append(
  2457. Entity(doc_id, entity_id, entity_text, entity_type, sentence_index, begin_index, end_index,
  2458. begin_index_temp, end_index_temp,in_attachment=in_attachment))
  2459. # 服务期限提取 2020/12/30 新增
  2460. list_servicetime = extract_servicetime(sentence_text)
  2461. entity_type = "serviceTime"
  2462. for servicetime in list_servicetime:
  2463. begin_index_temp = servicetime['begin_index']
  2464. for j in range(len(list_tokenbegin)):
  2465. if list_tokenbegin[j] == begin_index_temp:
  2466. begin_index = j
  2467. break
  2468. elif list_tokenbegin[j] > begin_index_temp:
  2469. begin_index = j - 1
  2470. break
  2471. index = servicetime['end_index']
  2472. end_index_temp = index
  2473. for j in range(begin_index, len(list_tokenbegin)):
  2474. if list_tokenbegin[j] >= index:
  2475. end_index = j - 1
  2476. break
  2477. entity_id = "%s_%d_%d_%d" % (doc_id, sentence_index, begin_index, end_index)
  2478. entity_text = servicetime['body']
  2479. list_sentence_entitys.append(
  2480. Entity(doc_id, entity_id, entity_text, entity_type, sentence_index, begin_index, end_index,
  2481. begin_index_temp, end_index_temp,in_attachment=in_attachment, prob=servicetime["prob"]))
  2482. # 招标方式提取 2020/12/30 新增
  2483. # list_bidway = extract_bidway(sentence_text, )
  2484. # entity_type = "bidway"
  2485. # for bidway in list_bidway:
  2486. # begin_index_temp = bidway['begin_index']
  2487. # end_index_temp = bidway['end_index']
  2488. # begin_index = changeIndexFromWordToWords(tokens, begin_index_temp)
  2489. # end_index = changeIndexFromWordToWords(tokens, end_index_temp)
  2490. # if begin_index is None or end_index is None:
  2491. # continue
  2492. # print(begin_index_temp,end_index_temp,begin_index,end_index)
  2493. # entity_id = "%s_%d_%d_%d" % (doc_id, sentence_index, begin_index, end_index)
  2494. # entity_text = bidway['body']
  2495. # list_sentence_entitys.append(
  2496. # Entity(doc_id, entity_id, entity_text, entity_type, sentence_index, begin_index, end_index,
  2497. # begin_index_temp, end_index_temp))
  2498. # 2021/12/29 新增比率提取
  2499. list_ratio = extract_ratio(sentence_text)
  2500. entity_type = "ratio"
  2501. for ratio in list_ratio:
  2502. # print("ratio", ratio)
  2503. begin_index_temp = ratio['begin_index']
  2504. for j in range(len(list_tokenbegin)):
  2505. if list_tokenbegin[j] == begin_index_temp:
  2506. begin_index = j
  2507. break
  2508. elif list_tokenbegin[j] > begin_index_temp:
  2509. begin_index = j - 1
  2510. break
  2511. index = ratio['end_index']
  2512. end_index_temp = index
  2513. for j in range(begin_index, len(list_tokenbegin)):
  2514. if list_tokenbegin[j] >= index:
  2515. end_index = j - 1
  2516. break
  2517. entity_id = "%s_%d_%d_%d" % (doc_id, sentence_index, begin_index, end_index)
  2518. entity_text = ratio['body']
  2519. list_sentence_entitys.append(
  2520. Entity(doc_id, entity_id, entity_text, entity_type, sentence_index, begin_index, end_index,
  2521. begin_index_temp, end_index_temp,in_attachment=in_attachment))
  2522. list_sentence_entitys.sort(key=lambda x:x.begin_index)
  2523. list_entitys_temp = list_entitys_temp+list_sentence_entitys
  2524. # 补充ner模型未识别全的company/org实体
  2525. for sentence_index in range(len(list_sentence)):
  2526. sentence_text = list_sentence[sentence_index].sentence_text
  2527. tokens = list_sentence[sentence_index].tokens
  2528. doc_id = list_sentence[sentence_index].doc_id
  2529. in_attachment = list_sentence[sentence_index].in_attachment
  2530. list_tokenbegin = []
  2531. begin = 0
  2532. for i in range(0, len(tokens)):
  2533. list_tokenbegin.append(begin)
  2534. begin += len(str(tokens[i]))
  2535. list_tokenbegin.append(begin + 1)
  2536. add_sentence_entitys = []
  2537. company_dict = sorted(list(company_dict),key=lambda x:len(x[1]),reverse=True)
  2538. for company_type,company_text in company_dict:
  2539. begin_index_list = findAllIndex(company_text,sentence_text)
  2540. for begin_index in begin_index_list:
  2541. is_continue = False
  2542. for t_begin,t_end in list(company_index[sentence_index]):
  2543. if begin_index>=t_begin and begin_index+len(company_text)<=t_end:
  2544. is_continue = True
  2545. break
  2546. if not is_continue:
  2547. add_sentence_entitys.append((begin_index,begin_index+len(company_text),company_type,company_text))
  2548. company_index[sentence_index].add((begin_index,begin_index+len(company_text)))
  2549. else:
  2550. continue
  2551. for ner_entity in add_sentence_entitys:
  2552. begin_index_temp = ner_entity[0]
  2553. end_index_temp = ner_entity[1]
  2554. entity_type = ner_entity[2]
  2555. entity_text = ner_entity[3]
  2556. if entity_type in ["org","company"] and not isLegalEnterprise(entity_text):
  2557. continue
  2558. for j in range(len(list_tokenbegin)):
  2559. if list_tokenbegin[j]==begin_index_temp:
  2560. begin_index = j
  2561. break
  2562. elif list_tokenbegin[j]>begin_index_temp:
  2563. begin_index = j-1
  2564. break
  2565. begin_index_temp += len(str(entity_text))
  2566. for j in range(begin_index,len(list_tokenbegin)):
  2567. if list_tokenbegin[j]>=begin_index_temp:
  2568. end_index = j-1
  2569. break
  2570. entity_id = "%s_%d_%d_%d"%(doc_id,sentence_index,begin_index,end_index)
  2571. #去掉标点符号
  2572. entity_text = re.sub("[,,。:!&@$\*]","",entity_text)
  2573. entity_text = entity_text.replace("(","(").replace(")",")") if isinstance(entity_text,str) else entity_text
  2574. 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))
  2575. list_entitys_temp.sort(key=lambda x:(x.sentence_index,x.begin_index))
  2576. list_entitys.append(list_entitys_temp)
  2577. return list_entitys
  2578. def union_result(codeName,prem):
  2579. '''
  2580. @summary:模型的结果拼成字典
  2581. @param:
  2582. codeName:编号名称模型的结果字典
  2583. prem:拿到属性的角色的字典
  2584. @return:拼接起来的字典
  2585. '''
  2586. result = []
  2587. assert len(codeName)==len(prem)
  2588. for item_code,item_prem in zip(codeName,prem):
  2589. result.append(dict(item_code,**item_prem))
  2590. return result
  2591. def persistenceData(data):
  2592. '''
  2593. @summary:将中间结果保存到数据库-线上生产的时候不需要执行
  2594. '''
  2595. import psycopg2
  2596. conn = psycopg2.connect(dbname="BiddingKG",user="postgres",password="postgres",host="192.168.2.101")
  2597. cursor = conn.cursor()
  2598. for item_index in range(len(data)):
  2599. item = data[item_index]
  2600. doc_id = item[0]
  2601. dic = item[1]
  2602. code = dic['code']
  2603. name = dic['name']
  2604. prem = dic['prem']
  2605. if len(code)==0:
  2606. code_insert = ""
  2607. else:
  2608. code_insert = ";".join(code)
  2609. prem_insert = ""
  2610. for item in prem:
  2611. for x in item:
  2612. if isinstance(x, list):
  2613. if len(x)>0:
  2614. for x1 in x:
  2615. prem_insert+="/".join(x1)+","
  2616. prem_insert+="$"
  2617. else:
  2618. prem_insert+=str(x)+"$"
  2619. prem_insert+=";"
  2620. sql = " insert into predict_validation(doc_id,code,name,prem) values('"+doc_id+"','"+code_insert+"','"+name+"','"+prem_insert+"')"
  2621. cursor.execute(sql)
  2622. conn.commit()
  2623. conn.close()
  2624. def persistenceData1(list_entitys,list_sentences):
  2625. '''
  2626. @summary:将中间结果保存到数据库-线上生产的时候不需要执行
  2627. '''
  2628. import psycopg2
  2629. conn = psycopg2.connect(dbname="BiddingKG",user="postgres",password="postgres",host="192.168.2.101")
  2630. cursor = conn.cursor()
  2631. for list_entity in list_entitys:
  2632. for entity in list_entity:
  2633. if entity.values is not None:
  2634. 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)+")"
  2635. else:
  2636. 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)+")"
  2637. cursor.execute(sql)
  2638. for list_sentence in list_sentences:
  2639. for sentence in list_sentence:
  2640. str_tokens = "["
  2641. for item in sentence.tokens:
  2642. str_tokens += "'"
  2643. if item=="'":
  2644. str_tokens += "''"
  2645. else:
  2646. str_tokens += item
  2647. str_tokens += "',"
  2648. str_tokens = str_tokens[:-1]+"]"
  2649. sql = " insert into predict_sentences(doc_id,sentence_index,tokens) values('"+sentence.doc_id+"',"+str(sentence.sentence_index)+",array"+str_tokens+")"
  2650. cursor.execute(sql)
  2651. conn.commit()
  2652. conn.close()
  2653. def _handle(item,result_queue):
  2654. dochtml = item["dochtml"]
  2655. docid = item["docid"]
  2656. list_innerTable = tableToText(BeautifulSoup(dochtml,"lxml"))
  2657. flag = False
  2658. if list_innerTable:
  2659. flag = True
  2660. for table in list_innerTable:
  2661. result_queue.put({"docid":docid,"json_table":json.dumps(table,ensure_ascii=False)})
  2662. def getPredictTable():
  2663. filename = "D:\Workspace2016\DataExport\data\websouce_doc.csv"
  2664. import pandas as pd
  2665. import json
  2666. from BiddingKG.dl.common.MultiHandler import MultiHandler,Queue
  2667. df = pd.read_csv(filename)
  2668. df_data = {"json_table":[],"docid":[]}
  2669. _count = 0
  2670. _sum = len(df["docid"])
  2671. task_queue = Queue()
  2672. result_queue = Queue()
  2673. _index = 0
  2674. for dochtml,docid in zip(df["dochtmlcon"],df["docid"]):
  2675. task_queue.put({"docid":docid,"dochtml":dochtml,"json_table":None})
  2676. _index += 1
  2677. mh = MultiHandler(task_queue=task_queue,task_handler=_handle,result_queue=result_queue,process_count=5,thread_count=1)
  2678. mh.run()
  2679. while True:
  2680. try:
  2681. item = result_queue.get(block=True,timeout=1)
  2682. df_data["docid"].append(item["docid"])
  2683. df_data["json_table"].append(item["json_table"])
  2684. except Exception as e:
  2685. print(e)
  2686. break
  2687. df_1 = pd.DataFrame(df_data)
  2688. df_1.to_csv("../form/websource_67000_table.csv",columns=["docid","json_table"])
  2689. if __name__=="__main__":
  2690. '''
  2691. import glob
  2692. for file in glob.glob("C:\\Users\\User\\Desktop\\test\\*.html"):
  2693. file_txt = str(file).replace("html","txt")
  2694. with codecs.open(file_txt,"a+",encoding="utf8") as f:
  2695. f.write("\n================\n")
  2696. content = codecs.open(file,"r",encoding="utf8").read()
  2697. f.write(segment(tableToText(BeautifulSoup(content,"lxml"))))
  2698. '''
  2699. # content = codecs.open("C:\\Users\\User\\Desktop\\2.html","r",encoding="utf8").read()
  2700. # print(segment(tableToText(BeautifulSoup(content,"lxml"))))
  2701. # getPredictTable()
  2702. with open('D:/138786703.html', 'r', encoding='utf-8') as f:
  2703. sourceContent = f.read()
  2704. # article_processed = segment(tableToText(BeautifulSoup(sourceContent, "lxml")))
  2705. # print(article_processed)
  2706. list_articles, list_sentences, list_entitys, _cost_time = get_preprocessed([['doc_id', sourceContent, "", "", '', '2021-02-01']], useselffool=True)
  2707. for entity in list_entitys[0]:
  2708. print(entity.entity_type, entity.entity_text)