Preprocessing.py 138 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821
  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. inner_table[i][j] = inner_table[i][j][0]
  390. # 模型预测表头
  391. predict_list = predict(inner_table)
  392. with open(r"C:\Users\Administrator\Desktop\table_head_test.txt", "a") as f:
  393. for i in range(len(predict_list)):
  394. f.write(str(i) + " " + str(inner_table[i]) + "\n")
  395. f.write(str(i) + " " + str(predict_list[i]) + "\n")
  396. f.write("\n")
  397. # print("table_list", inner_table)
  398. # print("predict_list", predict_list)
  399. for i in range(len(inner_table)):
  400. for j in range(len(inner_table[i])):
  401. inner_table[i][j] = [inner_table[i][j], int(predict_list[i][j])]
  402. head_list = sliceTable(inner_table)
  403. return inner_table, head_list
  404. def setHead_incontext(inner_table,pat_head,fix_value="~~",prob_min=0.5):
  405. data_x,data_position = getPredictor("form").getModel("context").encode(inner_table)
  406. predict_y = getPredictor("form").getModel("context").predict(data_x)
  407. for _position,_y in zip(data_position,predict_y):
  408. _w = _position[0]
  409. _h = _position[1]
  410. if _y[1]>prob_min:
  411. inner_table[_h][_w][1] = 1
  412. else:
  413. inner_table[_h][_w][1] = 0
  414. _item = inner_table[_h][_w][0]
  415. if re.search(pat_head,_item) is not None and len(_item)<8:
  416. inner_table[_h][_w][1] = 1
  417. # print("=====")
  418. # for item in inner_table:
  419. # print(item)
  420. # print("======")
  421. height = len(inner_table)
  422. width = len(inner_table[0])
  423. for i in range(height):
  424. for j in range(width):
  425. if re.search("[::]$", inner_table[i][j][0]) and len(inner_table[i][j][0])<8:
  426. inner_table[i][j][1] = 1
  427. repairTable(inner_table)
  428. head_list = sliceTable(inner_table)
  429. # print("inner_table:",inner_table)
  430. return inner_table,head_list
  431. #设置表头
  432. def setHead_inline(inner_table,prob_min=0.64):
  433. pad_row = "@@"
  434. pad_col = "##"
  435. removePadding(inner_table, pad_row, pad_col)
  436. pad_pattern = re.compile(pad_row+"|"+pad_col)
  437. height = len(inner_table)
  438. width = len(inner_table[0])
  439. head_list = []
  440. head_list.append(0)
  441. #行表头
  442. is_head_last = False
  443. for i in range(height):
  444. is_head = False
  445. is_long_value = False
  446. #判断是否是全padding值
  447. is_same_value = True
  448. same_value = inner_table[i][0][0]
  449. for j in range(width):
  450. if inner_table[i][j][0]!=same_value and inner_table[i][j][0]!=pad_row:
  451. is_same_value = False
  452. break
  453. #predict is head or not with model
  454. temp_item = ""
  455. for j in range(width):
  456. temp_item += inner_table[i][j][0]+"|"
  457. temp_item = re.sub(pad_pattern,"",temp_item)
  458. form_prob = getPredictor("form").predict(formEncoding(temp_item,expand=True),type="line")
  459. if form_prob is not None:
  460. if form_prob[0][1]>prob_min:
  461. is_head = True
  462. else:
  463. is_head = False
  464. #print(temp_item,form_prob)
  465. if len(inner_table[i][0][0])>40:
  466. is_long_value = True
  467. if is_head or is_long_value or is_same_value:
  468. #不把连续表头分开
  469. if not is_head_last:
  470. head_list.append(i)
  471. if is_long_value or is_same_value:
  472. head_list.append(i+1)
  473. if is_head:
  474. for j in range(width):
  475. inner_table[i][j][1] = 1
  476. is_head_last = is_head
  477. head_list.append(height)
  478. #列表头
  479. for i in range(len(head_list)-1):
  480. head_begin = head_list[i]
  481. head_end = head_list[i+1]
  482. #最后一列不设置为列表头
  483. for i in range(width-1):
  484. is_head = False
  485. #predict is head or not with model
  486. temp_item = ""
  487. for j in range(head_begin,head_end):
  488. temp_item += inner_table[j][i][0]+"|"
  489. temp_item = re.sub(pad_pattern,"",temp_item)
  490. form_prob = getPredictor("form").predict(formEncoding(temp_item,expand=True),type="line")
  491. if form_prob is not None:
  492. if form_prob[0][1]>prob_min:
  493. is_head = True
  494. else:
  495. is_head = False
  496. if is_head:
  497. for j in range(head_begin,head_end):
  498. inner_table[j][i][1] = 2
  499. addPadding(inner_table, pad_row, pad_col)
  500. return inner_table,head_list
  501. #设置表头
  502. def setHead_withRule(inner_table,pattern,pat_value,count):
  503. height = len(inner_table)
  504. width = len(inner_table[0])
  505. head_list = []
  506. head_list.append(0)
  507. #行表头
  508. is_head_last = False
  509. for i in range(height):
  510. set_match = set()
  511. is_head = False
  512. is_long_value = False
  513. is_same_value = True
  514. same_value = inner_table[i][0][0]
  515. for j in range(width):
  516. if inner_table[i][j][0]!=same_value:
  517. is_same_value = False
  518. break
  519. for j in range(width):
  520. if re.search(pat_value,inner_table[i][j][0]) is not None:
  521. is_head = False
  522. break
  523. str_find = re.findall(pattern,inner_table[i][j][0])
  524. if len(str_find)>0:
  525. set_match.add(inner_table[i][j][0])
  526. if len(set_match)>=count:
  527. is_head = True
  528. if len(inner_table[i][0][0])>40:
  529. is_long_value = True
  530. if is_head or is_long_value or is_same_value:
  531. if not is_head_last:
  532. head_list.append(i)
  533. if is_head:
  534. for j in range(width):
  535. inner_table[i][j][1] = 1
  536. is_head_last = is_head
  537. head_list.append(height)
  538. #列表头
  539. for i in range(len(head_list)-1):
  540. head_begin = head_list[i]
  541. head_end = head_list[i+1]
  542. #最后一列不设置为列表头
  543. for i in range(width-1):
  544. set_match = set()
  545. is_head = False
  546. for j in range(head_begin,head_end):
  547. if re.search(pat_value,inner_table[j][i][0]) is not None:
  548. is_head = False
  549. break
  550. str_find = re.findall(pattern,inner_table[j][i][0])
  551. if len(str_find)>0:
  552. set_match.add(inner_table[j][i][0])
  553. if len(set_match)>=count:
  554. is_head = True
  555. if is_head:
  556. for j in range(head_begin,head_end):
  557. inner_table[j][i][1] = 2
  558. return inner_table,head_list
  559. #取得表格的处理方向
  560. def getDirect(inner_table,begin,end):
  561. '''
  562. column_head = set()
  563. row_head = set()
  564. widths = len(inner_table[0])
  565. for height in range(begin,end):
  566. for width in range(widths):
  567. if inner_table[height][width][1] ==1:
  568. row_head.add(height)
  569. if inner_table[height][width][1] ==2:
  570. column_head.add(width)
  571. company_pattern = re.compile("公司")
  572. if 0 in column_head and begin not in row_head:
  573. return "column"
  574. if 0 in column_head and begin in row_head:
  575. for height in range(begin,end):
  576. count = 0
  577. count_flag = True
  578. for width_index in range(width):
  579. if inner_table[height][width_index][1]==0:
  580. if re.search(company_pattern,inner_table[height][width_index][0]) is not None:
  581. count += 1
  582. else:
  583. count_flag = False
  584. if count_flag and count>=2:
  585. return "column"
  586. return "row"
  587. '''
  588. count_row_keys = 0
  589. count_column_keys = 0
  590. width = len(inner_table[0])
  591. if begin<end:
  592. for w in range(len(inner_table[begin])):
  593. if inner_table[begin][w][1]!=0:
  594. count_row_keys += 1
  595. for h in range(begin,end):
  596. if inner_table[h][0][1]!=0:
  597. count_column_keys += 1
  598. company_pattern = re.compile("有限(责任)?公司")
  599. for height in range(begin,end):
  600. count_set = set()
  601. count_flag = True
  602. for width_index in range(width):
  603. if inner_table[height][width_index][1]==0:
  604. if re.search(company_pattern,inner_table[height][width_index][0]) is not None:
  605. count_set.add(inner_table[height][width_index][0])
  606. else:
  607. count_flag = False
  608. if count_flag and len(count_set)>=2:
  609. return "column"
  610. # if count_column_keys>count_row_keys: #2022/2/15 此项不够严谨,造成很多错误,故取消
  611. # return "column"
  612. return "row"
  613. #根据表格处理方向生成句子,
  614. def getTableText(inner_table,head_list,key_direct=False):
  615. # packPattern = "(标包|[标包][号段名])"
  616. packPattern = "(标包|标的|[标包][号段名]|((项目|物资|设备|场次|标段|标的|产品)(名称)))" # 2020/11/23 大网站规则,补充采购类包名
  617. rankPattern = "(排名|排序|名次|序号|评标结果|评审结果|是否中标|推荐意见)" # 2020/11/23 大网站规则,添加序号为排序
  618. entityPattern = "((候选|([中投]标|报价))(单位|公司|人|供应商))"
  619. moneyPattern = "([中投]标|报价)(金额|价)"
  620. height = len(inner_table)
  621. width = len(inner_table[0])
  622. text = ""
  623. for head_i in range(len(head_list)-1):
  624. head_begin = head_list[head_i]
  625. head_end = head_list[head_i+1]
  626. direct = getDirect(inner_table, head_begin, head_end)
  627. #若只有一行,则直接按行读取
  628. if head_end-head_begin==1:
  629. text_line = ""
  630. for i in range(head_begin,head_end):
  631. for w in range(len(inner_table[i])):
  632. if inner_table[i][w][1]==1:
  633. _punctuation = ":"
  634. else:
  635. _punctuation = "," #2021/12/15 统一为中文标点,避免 206893924 国际F座1108,1,009,197.49元
  636. if w>0:
  637. if inner_table[i][w][0]!= inner_table[i][w-1][0]:
  638. text_line += inner_table[i][w][0]+_punctuation
  639. else:
  640. text_line += inner_table[i][w][0]+_punctuation
  641. text_line = text_line+"。" if text_line!="" else text_line
  642. text += text_line
  643. else:
  644. #构建一个共现矩阵
  645. table_occurence = []
  646. for i in range(head_begin,head_end):
  647. line_oc = []
  648. for j in range(width):
  649. cell = inner_table[i][j]
  650. line_oc.append({"text":cell[0],"type":cell[1],"occu_count":0,"left_head":"","top_head":"","left_dis":0,"top_dis":0})
  651. table_occurence.append(line_oc)
  652. occu_height = len(table_occurence)
  653. occu_width = len(table_occurence[0]) if len(table_occurence)>0 else 0
  654. #为每个属性值寻找表头
  655. for i in range(occu_height):
  656. for j in range(occu_width):
  657. cell = table_occurence[i][j]
  658. #是属性值
  659. if cell["type"]==0 and cell["text"]!="":
  660. left_head = ""
  661. top_head = ""
  662. find_flag = False
  663. temp_head = ""
  664. for loop_i in range(1,i+1):
  665. if not key_direct:
  666. key_values = [1,2]
  667. else:
  668. key_values = [1]
  669. if table_occurence[i-loop_i][j]["type"] in key_values:
  670. if find_flag:
  671. if table_occurence[i-loop_i][j]["text"]!=temp_head:
  672. top_head = table_occurence[i-loop_i][j]["text"]+":"+top_head
  673. else:
  674. top_head = table_occurence[i-loop_i][j]["text"]+":"+top_head
  675. find_flag = True
  676. temp_head = table_occurence[i-loop_i][j]["text"]
  677. table_occurence[i-loop_i][j]["occu_count"] += 1
  678. else:
  679. #找到表头后遇到属性值就返回
  680. if find_flag:
  681. break
  682. cell["top_head"] += top_head
  683. find_flag = False
  684. temp_head = ""
  685. for loop_j in range(1,j+1):
  686. if not key_direct:
  687. key_values = [1,2]
  688. else:
  689. key_values = [2]
  690. if table_occurence[i][j-loop_j]["type"] in key_values:
  691. if find_flag:
  692. if table_occurence[i][j-loop_j]["text"]!=temp_head:
  693. left_head = table_occurence[i][j-loop_j]["text"]+":"+left_head
  694. else:
  695. left_head = table_occurence[i][j-loop_j]["text"]+":"+left_head
  696. find_flag = True
  697. temp_head = table_occurence[i][j-loop_j]["text"]
  698. table_occurence[i][j-loop_j]["occu_count"] += 1
  699. else:
  700. if find_flag:
  701. break
  702. cell["left_head"] += left_head
  703. if direct=="row":
  704. for i in range(occu_height):
  705. pack_text = ""
  706. rank_text = ""
  707. entity_text = ""
  708. text_line = ""
  709. money_text = ""
  710. #在同一句话中重复的可以去掉
  711. text_set = set()
  712. for j in range(width):
  713. cell = table_occurence[i][j]
  714. if cell["type"]==0 or (cell["type"]==1 and cell["occu_count"]==0):
  715. cell = table_occurence[i][j]
  716. head = (cell["top_head"]+":") if len(cell["top_head"])>0 else ""
  717. if re.search("单报标限总]价|金额|成交报?价|报价", head):
  718. head = cell["left_head"] + head
  719. else:
  720. head += cell["left_head"]
  721. if str(head+cell["text"]) in text_set:
  722. continue
  723. if re.search(packPattern,head) is not None:
  724. pack_text += head+cell["text"]+","
  725. elif re.search(rankPattern,head) is not None: # 2020/11/23 大网站规则发现问题,if 改elif
  726. #排名替换为同一种表达
  727. rank_text += head+cell["text"]+","
  728. #print(rank_text)
  729. elif re.search(entityPattern,head) is not None:
  730. entity_text += head+cell["text"]+","
  731. #print(entity_text)
  732. else:
  733. if re.search(moneyPattern,head) is not None and entity_text!="":
  734. money_text += head+cell["text"]+","
  735. else:
  736. text_line += head+cell["text"]+","
  737. text_set.add(str(head+cell["text"]))
  738. text += pack_text+rank_text+entity_text+money_text+text_line
  739. text = text[:-1]+"。" if len(text)>0 else text
  740. else:
  741. for j in range(occu_width):
  742. pack_text = ""
  743. rank_text = ""
  744. entity_text = ""
  745. text_line = ""
  746. text_set = set()
  747. for i in range(occu_height):
  748. cell = table_occurence[i][j]
  749. if cell["type"]==0 or (cell["type"]==1 and cell["occu_count"]==0):
  750. cell = table_occurence[i][j]
  751. head = (cell["left_head"]+"") if len(cell["left_head"])>0 else ""
  752. if re.search("单报标限总]价|金额|成交报?价|报价", head):
  753. head = cell["top_head"] + head
  754. else:
  755. head += cell["top_head"]
  756. if str(head+cell["text"]) in text_set:
  757. continue
  758. if re.search(packPattern,head) is not None:
  759. pack_text += head+cell["text"]+","
  760. elif re.search(rankPattern,head) is not None: # 2020/11/23 大网站规则发现问题,if 改elif
  761. #排名替换为同一种表达
  762. rank_text += head+cell["text"]+","
  763. #print(rank_text)
  764. elif re.search(entityPattern,head) is not None and \
  765. re.search('业绩|资格|条件',head)==None and re.search('业绩',cell["text"])==None : #2021/10/19 解决包含业绩的行调到前面问题
  766. entity_text += head+cell["text"]+","
  767. #print(entity_text)
  768. else:
  769. text_line += head+cell["text"]+","
  770. text_set.add(str(head+cell["text"]))
  771. text += pack_text+rank_text+entity_text+text_line
  772. text = text[:-1]+"。" if len(text)>0 else text
  773. # if direct=="row":
  774. # for i in range(head_begin,head_end):
  775. # pack_text = ""
  776. # rank_text = ""
  777. # entity_text = ""
  778. # text_line = ""
  779. # #在同一句话中重复的可以去掉
  780. # text_set = set()
  781. # for j in range(width):
  782. # cell = inner_table[i][j]
  783. # #是属性值
  784. # if cell[1]==0 and cell[0]!="":
  785. # head = ""
  786. #
  787. # find_flag = False
  788. # temp_head = ""
  789. # for loop_i in range(0,i+1-head_begin):
  790. # if not key_direct:
  791. # key_values = [1,2]
  792. # else:
  793. # key_values = [1]
  794. # if inner_table[i-loop_i][j][1] in key_values:
  795. # if find_flag:
  796. # if inner_table[i-loop_i][j][0]!=temp_head:
  797. # head = inner_table[i-loop_i][j][0]+":"+head
  798. # else:
  799. # head = inner_table[i-loop_i][j][0]+":"+head
  800. # find_flag = True
  801. # temp_head = inner_table[i-loop_i][j][0]
  802. # else:
  803. # #找到表头后遇到属性值就返回
  804. # if find_flag:
  805. # break
  806. #
  807. # find_flag = False
  808. # temp_head = ""
  809. #
  810. #
  811. #
  812. # for loop_j in range(1,j+1):
  813. # if not key_direct:
  814. # key_values = [1,2]
  815. # else:
  816. # key_values = [2]
  817. # if inner_table[i][j-loop_j][1] in key_values:
  818. # if find_flag:
  819. # if inner_table[i][j-loop_j][0]!=temp_head:
  820. # head = inner_table[i][j-loop_j][0]+":"+head
  821. # else:
  822. # head = inner_table[i][j-loop_j][0]+":"+head
  823. # find_flag = True
  824. # temp_head = inner_table[i][j-loop_j][0]
  825. # else:
  826. # if find_flag:
  827. # break
  828. #
  829. # if str(head+inner_table[i][j][0]) in text_set:
  830. # continue
  831. # if re.search(packPattern,head) is not None:
  832. # pack_text += head+inner_table[i][j][0]+","
  833. # elif re.search(rankPattern,head) is not None: # 2020/11/23 大网站规则发现问题,if 改elif
  834. # #排名替换为同一种表达
  835. # rank_text += head+inner_table[i][j][0]+","
  836. # #print(rank_text)
  837. # elif re.search(entityPattern,head) is not None:
  838. # entity_text += head+inner_table[i][j][0]+","
  839. # #print(entity_text)
  840. # else:
  841. # text_line += head+inner_table[i][j][0]+","
  842. # text_set.add(str(head+inner_table[i][j][0]))
  843. # text += pack_text+rank_text+entity_text+text_line
  844. # text = text[:-1]+"。" if len(text)>0 else text
  845. # else:
  846. # for j in range(width):
  847. #
  848. # rank_text = ""
  849. # entity_text = ""
  850. # text_line = ""
  851. # text_set = set()
  852. # for i in range(head_begin,head_end):
  853. # cell = inner_table[i][j]
  854. # #是属性值
  855. # if cell[1]==0 and cell[0]!="":
  856. # find_flag = False
  857. # head = ""
  858. # temp_head = ""
  859. #
  860. # for loop_j in range(1,j+1):
  861. # if not key_direct:
  862. # key_values = [1,2]
  863. # else:
  864. # key_values = [2]
  865. # if inner_table[i][j-loop_j][1] in key_values:
  866. # if find_flag:
  867. # if inner_table[i][j-loop_j][0]!=temp_head:
  868. # head = inner_table[i][j-loop_j][0]+":"+head
  869. # else:
  870. # head = inner_table[i][j-loop_j][0]+":"+head
  871. # find_flag = True
  872. # temp_head = inner_table[i][j-loop_j][0]
  873. # else:
  874. # if find_flag:
  875. # break
  876. # find_flag = False
  877. # temp_head = ""
  878. # for loop_i in range(0,i+1-head_begin):
  879. # if not key_direct:
  880. # key_values = [1,2]
  881. # else:
  882. # key_values = [1]
  883. # if inner_table[i-loop_i][j][1] in key_values:
  884. # if find_flag:
  885. # if inner_table[i-loop_i][j][0]!=temp_head:
  886. # head = inner_table[i-loop_i][j][0]+":"+head
  887. # else:
  888. # head = inner_table[i-loop_i][j][0]+":"+head
  889. # find_flag = True
  890. # temp_head = inner_table[i-loop_i][j][0]
  891. # else:
  892. # if find_flag:
  893. # break
  894. # if str(head+inner_table[i][j][0]) in text_set:
  895. # continue
  896. # if re.search(rankPattern,head) is not None:
  897. # rank_text += head+inner_table[i][j][0]+","
  898. # #print(rank_text)
  899. # elif re.search(entityPattern,head) is not None:
  900. # entity_text += head+inner_table[i][j][0]+","
  901. # #print(entity_text)
  902. # else:
  903. # text_line += head+inner_table[i][j][0]+","
  904. # text_set.add(str(head+inner_table[i][j][0]))
  905. # text += rank_text+entity_text+text_line
  906. # text = text[:-1]+"。" if len(text)>0 else text
  907. return text
  908. def removeFix(inner_table,fix_value="~~"):
  909. height = len(inner_table)
  910. width = len(inner_table[0])
  911. for h in range(height):
  912. for w in range(width):
  913. if inner_table[h][w][0]==fix_value:
  914. inner_table[h][w][0] = ""
  915. def trunTable(tbody,in_attachment):
  916. # print(tbody.find('tbody'))
  917. # 附件中的表格,排除异常错乱的表格
  918. if in_attachment:
  919. if tbody.name=='table':
  920. _tbody = tbody.find('tbody')
  921. if _tbody is None:
  922. _tbody = tbody
  923. else:
  924. _tbody = tbody
  925. _td_len_list = []
  926. for _tr in _tbody.find_all(recursive=False):
  927. len_td = len(_tr.find_all(recursive=False))
  928. _td_len_list.append(len_td)
  929. if len(list(set(_td_len_list)))>8:
  930. return None
  931. fixSpan(tbody)
  932. inner_table = getTable(tbody)
  933. inner_table = fixTable(inner_table)
  934. if len(inner_table)>0 and len(inner_table[0])>0:
  935. #inner_table,head_list = setHead_withRule(inner_table,pat_head,pat_value,3)
  936. #inner_table,head_list = setHead_inline(inner_table)
  937. inner_table, head_list = setHead_initem(inner_table,pat_head)
  938. # inner_table, head_list = set_head_model(inner_table)
  939. # inner_table,head_list = setHead_incontext(inner_table,pat_head)
  940. # print(inner_table)
  941. # for begin in range(len(head_list[:-1])):
  942. # for item in inner_table[head_list[begin]:head_list[begin+1]]:
  943. # print(item)
  944. # print("====")
  945. removeFix(inner_table)
  946. # print("----")
  947. # print(head_list)
  948. # for item in inner_table:
  949. # print(item)
  950. tbody.string = getTableText(inner_table,head_list)
  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. return text
  1243. '''
  1244. #数据清洗
  1245. def segment(soup):
  1246. segList = ["title"]
  1247. commaList = ["p","div","h1", "h2", "h3", "h4", "h5", "h6", "header", "dl", "ul", "label"]
  1248. spaceList = ["span"]
  1249. tbodies = soup.find_all('tbody')
  1250. if len(tbodies) == 0:
  1251. tbodies = soup.find_all('table')
  1252. # 递归遍历所有节点,插入符号
  1253. for child in soup.find_all(recursive=True):
  1254. if child.name == 'br':
  1255. child.insert_before(',')
  1256. child_text = re.sub('\s', '', child.get_text())
  1257. if child_text == '' or child_text[-1] in ['。',',',':',';']:
  1258. continue
  1259. if child.name in segList:
  1260. child.insert_after("。")
  1261. if child.name in commaList:
  1262. if len(child_text)>3 and len(child_text) <50: # 先判断是否字数少于50,成立加逗号,否则加句号
  1263. child.insert_after(",")
  1264. elif len(child_text) >=50:
  1265. child.insert_after("。")
  1266. #if child.name in spaceList:
  1267. #child.insert_after(" ")
  1268. text = str(soup.get_text())
  1269. text = re.sub("\s{5,}",",",text)
  1270. text = text.replace('"',"“").replace("\r","").replace("\n",",")
  1271. #替换"""为"“",否则导入deepdive出错
  1272. text = text.replace('"',"“")
  1273. #text = text.replace('"',"“").replace("\r","").replace("\n","")
  1274. #删除所有空格
  1275. text = re.sub("\s+","#nbsp#",text)
  1276. text_list = text.split('#nbsp#')
  1277. new_text = ''
  1278. for i in range(len(text_list)-1):
  1279. if text_list[i] == '' or text_list[i][-1] in [',','。',';',':']:
  1280. new_text += text_list[i]
  1281. elif re.findall('([一二三四五六七八九]、)', text_list[i+1][:4]) != []:
  1282. new_text += text_list[i] + '。'
  1283. elif re.findall('([0-9]、)', text_list[i+1][:4]) != []:
  1284. new_text += text_list[i] + ';'
  1285. elif text_list[i].isdigit() and text_list[i+1].isdigit():
  1286. new_text += text_list[i] + ' '
  1287. elif text_list[i][-1] in ['-',':','(',')','/','(',')','——','年','月','日','时','分','¥'] or text_list[i+1][0] in ['-',':','(',')','/','(',')','——','年','月','日','时','分','元','万元']:
  1288. new_text += text_list[i]
  1289. elif len(text_list[i]) >= 3 and len(text_list[i+1]) >= 3:
  1290. new_text += text_list[i] + ','
  1291. else:
  1292. new_text += text_list[i]
  1293. new_text += text_list[-1]
  1294. text = new_text
  1295. #替换英文冒号为中文冒号
  1296. text = re.sub("(?<=[\u4e00-\u9fa5]):|:(?=[\u4e00-\u9fa5])",":",text)
  1297. #替换为中文逗号
  1298. text = re.sub("(?<=[\u4e00-\u9fa5]),|,(?=[\u4e00-\u9fa5])",",",text)
  1299. #替换为中文分号
  1300. text = re.sub("(?<=[\u4e00-\u9fa5]);|;(?=[\u4e00-\u9fa5])",";",text)
  1301. #替换标点
  1302. while(True):
  1303. #替换连续的标点
  1304. punc = re.search(",(?P<punc>:|。|,|;)\s*",text)
  1305. if punc is not None:
  1306. text = re.sub(","+punc.group("punc")+"\s*",punc.group("punc"),text)
  1307. punc = re.search("(?P<punc>:|。|,|;)\s*,",text)
  1308. if punc is not None:
  1309. text = re.sub(punc.group("punc")+"\s*,",punc.group("punc"),text)
  1310. else:
  1311. #替换标点之后的空格
  1312. punc = re.search("(?P<punc>:|。|,|;)\s+",text)
  1313. if punc is not None:
  1314. text = re.sub(punc.group("punc")+"\s+",punc.group("punc"),text)
  1315. else:
  1316. break
  1317. #将连续的中文句号替换为一个
  1318. text_split = text.split("。")
  1319. text_split = [x for x in text_split if len(x)>0]
  1320. text = "。".join(text_split)
  1321. #替换中文括号为英文括号
  1322. text = re.sub("(","(",text)
  1323. text = re.sub(")",")",text)
  1324. return text
  1325. '''
  1326. #连续实体合并(弃用)
  1327. def union_ner(list_ner):
  1328. result_list = []
  1329. union_index = []
  1330. union_index_set = set()
  1331. for i in range(len(list_ner)-1):
  1332. if len(set([str(list_ner[i][2]),str(list_ner[i+1][2])])&set(["org","company"]))==2:
  1333. if list_ner[i][1]-list_ner[i+1][0]==1:
  1334. union_index_set.add(i)
  1335. union_index_set.add(i+1)
  1336. union_index.append((i,i+1))
  1337. for i in range(len(list_ner)):
  1338. if i not in union_index_set:
  1339. result_list.append(list_ner[i])
  1340. for item in union_index:
  1341. #print(str(list_ner[item[0]][3])+str(list_ner[item[1]][3]))
  1342. 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])))
  1343. return result_list
  1344. # def get_preprocessed(articles,useselffool=False):
  1345. # '''
  1346. # @summary:预处理步骤,NLP处理、实体识别
  1347. # @param:
  1348. # articles:待处理的文章list [[id,source,jointime,doc_id,title]]
  1349. # @return:list of articles,list of each article of sentences,list of each article of entitys
  1350. # '''
  1351. # list_articles = []
  1352. # list_sentences = []
  1353. # list_entitys = []
  1354. # cost_time = dict()
  1355. # for article in articles:
  1356. # list_sentences_temp = []
  1357. # list_entitys_temp = []
  1358. # doc_id = article[0]
  1359. # sourceContent = article[1]
  1360. # _send_doc_id = article[3]
  1361. # _title = article[4]
  1362. # #表格处理
  1363. # key_preprocess = "tableToText"
  1364. # start_time = time.time()
  1365. # article_processed = segment(tableToText(BeautifulSoup(sourceContent,"lxml")))
  1366. #
  1367. # # log(article_processed)
  1368. #
  1369. # if key_preprocess not in cost_time:
  1370. # cost_time[key_preprocess] = 0
  1371. # cost_time[key_preprocess] += time.time()-start_time
  1372. #
  1373. # #article_processed = article[1]
  1374. # list_articles.append(Article(doc_id,article_processed,sourceContent,_send_doc_id,_title))
  1375. # #nlp处理
  1376. # if article_processed is not None and len(article_processed)!=0:
  1377. # split_patten = "。"
  1378. # sentences = []
  1379. # _begin = 0
  1380. # for _iter in re.finditer(split_patten,article_processed):
  1381. # sentences.append(article_processed[_begin:_iter.span()[1]])
  1382. # _begin = _iter.span()[1]
  1383. # sentences.append(article_processed[_begin:])
  1384. #
  1385. # lemmas = []
  1386. # doc_offsets = []
  1387. # dep_types = []
  1388. # dep_tokens = []
  1389. #
  1390. # time1 = time.time()
  1391. #
  1392. # '''
  1393. # tokens_all = fool.cut(sentences)
  1394. # #pos_all = fool.LEXICAL_ANALYSER.pos(tokens_all)
  1395. # #ner_tag_all = fool.LEXICAL_ANALYSER.ner_labels(sentences,tokens_all)
  1396. # ner_entitys_all = fool.ner(sentences)
  1397. # '''
  1398. # #限流执行
  1399. # key_nerToken = "nerToken"
  1400. # start_time = time.time()
  1401. # tokens_all,ner_entitys_all = getTokensAndNers(sentences,useselffool=useselffool)
  1402. # if key_nerToken not in cost_time:
  1403. # cost_time[key_nerToken] = 0
  1404. # cost_time[key_nerToken] += time.time()-start_time
  1405. #
  1406. #
  1407. # for sentence_index in range(len(sentences)):
  1408. #
  1409. #
  1410. #
  1411. # list_sentence_entitys = []
  1412. # sentence_text = sentences[sentence_index]
  1413. # tokens = tokens_all[sentence_index]
  1414. #
  1415. # list_tokenbegin = []
  1416. # begin = 0
  1417. # for i in range(0,len(tokens)):
  1418. # list_tokenbegin.append(begin)
  1419. # begin += len(str(tokens[i]))
  1420. # list_tokenbegin.append(begin+1)
  1421. # #pos_tag = pos_all[sentence_index]
  1422. # pos_tag = ""
  1423. #
  1424. # ner_entitys = ner_entitys_all[sentence_index]
  1425. #
  1426. # 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))
  1427. #
  1428. # #识别package
  1429. #
  1430. #
  1431. # #识别实体
  1432. # for ner_entity in ner_entitys:
  1433. # begin_index_temp = ner_entity[0]
  1434. # end_index_temp = ner_entity[1]
  1435. # entity_type = ner_entity[2]
  1436. # entity_text = ner_entity[3]
  1437. #
  1438. # for j in range(len(list_tokenbegin)):
  1439. # if list_tokenbegin[j]==begin_index_temp:
  1440. # begin_index = j
  1441. # break
  1442. # elif list_tokenbegin[j]>begin_index_temp:
  1443. # begin_index = j-1
  1444. # break
  1445. # begin_index_temp += len(str(entity_text))
  1446. # for j in range(begin_index,len(list_tokenbegin)):
  1447. # if list_tokenbegin[j]>=begin_index_temp:
  1448. # end_index = j-1
  1449. # break
  1450. # entity_id = "%s_%d_%d_%d"%(doc_id,sentence_index,begin_index,end_index)
  1451. #
  1452. # #去掉标点符号
  1453. # entity_text = re.sub("[,,。:]","",entity_text)
  1454. # 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))
  1455. #
  1456. #
  1457. # #使用正则识别金额
  1458. # entity_type = "money"
  1459. #
  1460. # #money_patten_str = "(([1-9][\d,,]*(?:\.\d+)?[百千万亿]?[\(\)()元整]+)|([零壹贰叁肆伍陆柒捌玖拾佰仟萬億十百千万亿元角分]{3,})|(?:[¥¥]+,?|报价|标价)[(\(]?([万])?元?[)\)]?[::]?.{,7}?([1-9][\d,,]*(?:\.\d+)?(?:,?)[百千万亿]?)|([1-9][\d,,]*(?:\.\d+)?(?:,?)[百千万亿]?)[\((]?([万元]{1,2}))*"
  1461. #
  1462. # list_money_pattern = {"cn":"(()()([零壹贰叁肆伍陆柒捌玖拾佰仟萬億十百千万亿元角分]{3,})())*",
  1463. # "key_word":"((?:[¥¥]+,?|[报标限]价|金额)(?:[(\(]?\s*([万元]*)\s*[)\)]?)\s*[::]?(\s*[^壹贰叁肆伍陆柒捌玖拾佰仟萬億分]{,7}?)([0-9][\d,,]*(?:\.\d+)?(?:,?)[百千万亿元]*)())*",
  1464. # "front_m":"((?:[(\(]?\s*([万元]+)\s*[)\)])\s*[::]?(\s*[^壹贰叁肆伍陆柒捌玖拾佰仟萬億分]{,7}?)([0-9][\d,,]*(?:\.\d+)?(?:,?)[百千万亿元]*)())*",
  1465. # "behind_m":"(()()([0-9][\d,,]*(?:\.\d+)?(?:,?)[百千万亿]*)[\((]?([万元]+)[\))]?)*"}
  1466. #
  1467. # set_begin = set()
  1468. # for pattern_key in list_money_pattern.keys():
  1469. # pattern = re.compile(list_money_pattern[pattern_key])
  1470. # all_match = re.findall(pattern, sentence_text)
  1471. # index = 0
  1472. # for i in range(len(all_match)):
  1473. # if len(all_match[i][0])>0:
  1474. # # print("===",all_match[i])
  1475. # #print(all_match[i][0])
  1476. # unit = ""
  1477. # entity_text = all_match[i][3]
  1478. # if pattern_key in ["key_word","front_m"]:
  1479. # unit = all_match[i][1]
  1480. # else:
  1481. # unit = all_match[i][4]
  1482. # if entity_text.find("元")>=0:
  1483. # unit = ""
  1484. #
  1485. # index += len(all_match[i][0])-len(entity_text)-len(all_match[i][4])#-len(all_match[i][1])-len(all_match[i][2])#整个提出来的作为实体->数字部分作为整体,否则会丢失特征
  1486. #
  1487. # begin_index_temp = index
  1488. # for j in range(len(list_tokenbegin)):
  1489. # if list_tokenbegin[j]==index:
  1490. # begin_index = j
  1491. # break
  1492. # elif list_tokenbegin[j]>index:
  1493. # begin_index = j-1
  1494. # break
  1495. # index += len(str(entity_text))+len(all_match[i][4])#+len(all_match[i][2])+len(all_match[i][1])#整个提出来的作为实体
  1496. # end_index_temp = index
  1497. # #index += len(str(all_match[i][0]))
  1498. # for j in range(begin_index,len(list_tokenbegin)):
  1499. # if list_tokenbegin[j]>=index:
  1500. # end_index = j-1
  1501. # break
  1502. # entity_id = "%s_%d_%d_%d"%(doc_id,sentence_index,begin_index,end_index)
  1503. #
  1504. #
  1505. # entity_text = re.sub("[^0-9.零壹贰叁肆伍陆柒捌玖拾佰仟萬億十百千万亿元角分]","",entity_text)
  1506. # if len(unit)>0:
  1507. # entity_text = str(getUnifyMoney(entity_text)*getMultipleFactor(unit[0]))
  1508. # else:
  1509. # entity_text = str(getUnifyMoney(entity_text))
  1510. #
  1511. # _exists = False
  1512. # for item in list_sentence_entitys:
  1513. # if item.entity_id==entity_id and item.entity_type==entity_type:
  1514. # _exists = True
  1515. # if not _exists:
  1516. # if float(entity_text)>10:
  1517. # 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))
  1518. #
  1519. # else:
  1520. # index += 1
  1521. #
  1522. # list_sentence_entitys.sort(key=lambda x:x.begin_index)
  1523. # list_entitys_temp = list_entitys_temp+list_sentence_entitys
  1524. # list_sentences.append(list_sentences_temp)
  1525. # list_entitys.append(list_entitys_temp)
  1526. # return list_articles,list_sentences,list_entitys,cost_time
  1527. def get_preprocessed(articles, useselffool=False):
  1528. '''
  1529. @summary:预处理步骤,NLP处理、实体识别
  1530. @param:
  1531. articles:待处理的文章list [[id,source,jointime,doc_id,title]]
  1532. @return:list of articles,list of each article of sentences,list of each article of entitys
  1533. '''
  1534. cost_time = dict()
  1535. list_articles = get_preprocessed_article(articles,cost_time)
  1536. list_sentences,list_outlines = get_preprocessed_sentences(list_articles,True,cost_time)
  1537. list_entitys = get_preprocessed_entitys(list_sentences,True,cost_time)
  1538. calibrateEnterprise(list_articles,list_sentences,list_entitys)
  1539. return list_articles,list_sentences,list_entitys,list_outlines,cost_time
  1540. def special_treatment(sourceContent, web_source_no):
  1541. if web_source_no == 'DX000202-1':
  1542. ser = re.search('中标供应商及中标金额:【((\w{5,20}-[\d,.]+,)+)】', sourceContent)
  1543. if ser:
  1544. new = ""
  1545. l = ser.group(1).split(',')
  1546. for i in range(len(l)):
  1547. it = l[i]
  1548. if '-' in it:
  1549. role, money = it.split('-')
  1550. new += '标段%d, 中标供应商: ' % (i + 1) + role + ',中标金额:' + money + '。'
  1551. sourceContent = sourceContent.replace(ser.group(0), new, 1)
  1552. elif web_source_no == '00753-14':
  1553. pcontent = sourceContent.find("div", id="pcontent")
  1554. pcontent = pcontent.find_all(recursive=False)[0]
  1555. first_table = None
  1556. for idx in range(len(pcontent.find_all(recursive=False))):
  1557. t_part = pcontent.find_all(recursive=False)[idx]
  1558. if t_part.name != "table":
  1559. break
  1560. if idx == 0:
  1561. first_table = t_part
  1562. else:
  1563. for _tr in t_part.find("tbody").find_all(recursive=False):
  1564. first_table.find("tbody").append(_tr)
  1565. t_part.clear()
  1566. elif web_source_no == 'DX008357-11':
  1567. pcontent = sourceContent.find("div", id="pcontent")
  1568. pcontent = pcontent.find_all(recursive=False)[0]
  1569. error_table = []
  1570. is_error_table = False
  1571. for part in pcontent.find_all(recursive=False):
  1572. if is_error_table:
  1573. if part.name == "table":
  1574. error_table.append(part)
  1575. else:
  1576. break
  1577. if part.name == "div" and part.get_text(strip=True) == "中标候选单位:":
  1578. is_error_table = True
  1579. first_table = None
  1580. for idx in range(len(error_table)):
  1581. t_part = error_table[idx]
  1582. # if t_part.name != "table":
  1583. # break
  1584. if idx == 0:
  1585. for _tr in t_part.find("tbody").find_all(recursive=False):
  1586. if _tr.get_text(strip=True) == "":
  1587. _tr.decompose()
  1588. first_table = t_part
  1589. else:
  1590. for _tr in t_part.find("tbody").find_all(recursive=False):
  1591. if _tr.get_text(strip=True) != "":
  1592. first_table.find("tbody").append(_tr)
  1593. t_part.clear()
  1594. elif web_source_no == '18021-2':
  1595. pcontent = sourceContent.find("div", id="pcontent")
  1596. td = pcontent.find_all("td")
  1597. for _td in td:
  1598. if str(_td.string).strip() == "报价金额":
  1599. _td.string = "单价"
  1600. elif web_source_no == '13740-2':
  1601. # “xxx成为成交供应商”
  1602. re_match = re.search("[^,。]+成为[^,。]*成交供应商", sourceContent)
  1603. if re_match:
  1604. sourceContent = sourceContent.replace(re_match.group(), "成交人:" + re_match.group(), sourceContent)
  1605. elif web_source_no == '03786-10':
  1606. ser1 = re.search('中标价:([\d,.]+)', sourceContent)
  1607. ser2 = re.search('合同金额[((]万元[))]:([\d,.]+)', sourceContent)
  1608. if ser1 and ser2:
  1609. m1 = ser1.group(1).replace(',', '')
  1610. m2 = ser2.group(1).replace(',', '')
  1611. if float(m1) < 100000 and (m1.split('.')[0] == m2.split('.')[0] or m2 == '0'):
  1612. new = '中标价(万元):' + m1
  1613. sourceContent = sourceContent.replace(ser1.group(0), new, 1)
  1614. elif web_source_no=='00076-4':
  1615. ser = re.search('主要标的数量:([0-9一]+)\w{,3},主要标的单价:([\d,.]+)元?,合同金额:(.00),', sourceContent)
  1616. if ser:
  1617. num = ser.group(1).replace('一', '1')
  1618. try:
  1619. num = 1 if num == '0' else num
  1620. unit_price = ser.group(2).replace(',', '')
  1621. total_price = str(int(num) * float(unit_price))
  1622. new = '合同金额:' + total_price
  1623. sourceContent = sourceContent.replace('合同金额:.00', new, 1)
  1624. except Exception as e:
  1625. log('preprocessing.py special_treatment exception')
  1626. elif web_source_no=='DX000105-2':
  1627. if re.search("成交公示", sourceContent) and re.search(',投标人:', sourceContent) and re.search(',成交人:', sourceContent)==None:
  1628. sourceContent = sourceContent.replace(',投标人:', ',成交人:')
  1629. elif web_source_no in ['04080-3', '04080-4']:
  1630. ser = re.search('合同金额:([0-9,]+.[0-9]{3,})(.{,4})', sourceContent)
  1631. if ser and '万' not in ser.group(2):
  1632. sourceContent = sourceContent.replace('合同金额:', '合同金额(万元):')
  1633. elif web_source_no=='03761-3':
  1634. ser = re.search('中标价,([0-9]+)[.0-9]*%', sourceContent)
  1635. if ser and int(ser.group(1))>100:
  1636. sourceContent = sourceContent.replace(ser.group(0), ser.group(0)[:-1]+'元')
  1637. elif web_source_no=='00695-7':
  1638. ser = re.search('支付金额:', sourceContent)
  1639. if ser:
  1640. sourceContent = sourceContent.replace('支付金额:', '合同金额:')
  1641. return sourceContent
  1642. def article_limit(soup,limit_words=30000):
  1643. sub_space = re.compile("\s+")
  1644. def soup_limit(_soup,_count,max_count=30000,max_gap=500):
  1645. """
  1646. :param _soup: soup
  1647. :param _count: 当前字数
  1648. :param max_count: 字数最大限制
  1649. :param max_gap: 超过限制后的最大误差
  1650. :return:
  1651. """
  1652. _gap = _count - max_count
  1653. _is_skip = False
  1654. next_soup = None
  1655. while len(_soup.find_all(recursive=False)) == 1 and \
  1656. _soup.get_text(strip=True) == _soup.find_all(recursive=False)[0].get_text(strip=True):
  1657. _soup = _soup.find_all(recursive=False)[0]
  1658. if len(_soup.find_all(recursive=False)) == 0:
  1659. _soup.string = str(_soup.get_text())[:max_count-_count]
  1660. _count += len(re.sub(sub_space, "", _soup.string))
  1661. _gap = _count - max_count
  1662. next_soup = None
  1663. else:
  1664. for _soup_part in _soup.find_all(recursive=False):
  1665. if not _is_skip:
  1666. _count += len(re.sub(sub_space, "", _soup_part.get_text()))
  1667. if _count >= max_count:
  1668. _gap = _count - max_count
  1669. if _gap <= max_gap:
  1670. _is_skip = True
  1671. else:
  1672. _is_skip = True
  1673. next_soup = _soup_part
  1674. _count -= len(re.sub(sub_space, "", _soup_part.get_text()))
  1675. continue
  1676. else:
  1677. _soup_part.decompose()
  1678. return _count,_gap,next_soup
  1679. text_count = 0
  1680. have_attachment = False
  1681. attachment_part = None
  1682. for child in soup.find_all(recursive=True):
  1683. if child.name == 'div' and 'class' in child.attrs:
  1684. if "richTextFetch" in child['class']:
  1685. child.insert_before("##attachment##")
  1686. attachment_part = child
  1687. have_attachment = True
  1688. break
  1689. if not have_attachment:
  1690. # 无附件
  1691. if len(re.sub(sub_space, "", soup.get_text())) > limit_words:
  1692. text_count,gap,n_soup = soup_limit(soup,text_count,max_count=limit_words,max_gap=500)
  1693. while n_soup:
  1694. text_count, gap, n_soup = soup_limit(n_soup, text_count, max_count=limit_words, max_gap=500)
  1695. else:
  1696. # 有附件
  1697. _text = re.sub(sub_space, "", soup.get_text())
  1698. _text_split = _text.split("##attachment##")
  1699. if len(_text_split[0])>limit_words:
  1700. main_soup = attachment_part.parent
  1701. main_text = main_soup.find_all(recursive=False)[0]
  1702. text_count, gap, n_soup = soup_limit(main_text, text_count, max_count=limit_words, max_gap=500)
  1703. while n_soup:
  1704. text_count, gap, n_soup = soup_limit(n_soup, text_count, max_count=limit_words, max_gap=500)
  1705. if len(_text_split[1])>limit_words:
  1706. # attachment_html纯文本,无子结构
  1707. if len(attachment_part.find_all(recursive=False))==0:
  1708. attachment_part.string = str(attachment_part.get_text())[:limit_words]
  1709. else:
  1710. attachment_text_nums = 0
  1711. attachment_skip = False
  1712. for part in attachment_part.find_all(recursive=False):
  1713. if not attachment_skip:
  1714. attachment_text_nums += len(re.sub(sub_space, "", part.get_text()))
  1715. if attachment_text_nums>=limit_words:
  1716. part.string = str(part.get_text())[:attachment_text_nums-limit_words]
  1717. attachment_skip = True
  1718. else:
  1719. part.decompose()
  1720. return soup
  1721. def get_preprocessed_article(articles,cost_time = dict(),useselffool=True):
  1722. '''
  1723. :param articles: 待处理的article source html
  1724. :param useselffool: 是否使用selffool
  1725. :return: list_articles
  1726. '''
  1727. list_articles = []
  1728. for article in articles:
  1729. doc_id = article[0]
  1730. sourceContent = article[1]
  1731. sourceContent = re.sub("<html>|</html>|<body>|</body>","",sourceContent)
  1732. sourceContent = sourceContent.replace('<br/>', '<br>')
  1733. sourceContent = re.sub("<br>(\s{0,}<br>)+","<br>",sourceContent)
  1734. # for br_match in re.findall("[^>]+?<br>",sourceContent):
  1735. # _new = re.sub("<br>","",br_match)
  1736. # # <br>标签替换为<p>标签
  1737. # if not re.search("^\s+$",_new):
  1738. # _new = '<p>'+_new + '</p>'
  1739. # # print(br_match,_new)
  1740. # sourceContent = sourceContent.replace(br_match,_new,1)
  1741. _send_doc_id = article[3]
  1742. _title = article[4]
  1743. page_time = article[5]
  1744. web_source_no = article[6]
  1745. '''特别数据源对 html 做特别修改'''
  1746. if web_source_no in ['DX000202-1']:
  1747. sourceContent = special_treatment(sourceContent, web_source_no)
  1748. #表格处理
  1749. key_preprocess = "tableToText"
  1750. start_time = time.time()
  1751. # article_processed = tableToText(BeautifulSoup(sourceContent,"lxml"))
  1752. article_processed = BeautifulSoup(sourceContent,"lxml")
  1753. '''特别数据源对 BeautifulSoup(html) 做特别修改'''
  1754. if web_source_no in ["00753-14","DX008357-11","18021-2"]:
  1755. article_processed = special_treatment(article_processed, web_source_no)
  1756. for _soup in article_processed.descendants:
  1757. # 识别无标签文本,添加<span>标签
  1758. if not _soup.name and not _soup.parent.string and _soup.string.strip()!="":
  1759. # print(_soup.parent.string,_soup.string.strip())
  1760. _soup.wrap(article_processed.new_tag("span"))
  1761. # print(article_processed)
  1762. # 正文和附件内容限制字数30000
  1763. article_processed = article_limit(article_processed,limit_words=30000)
  1764. article_processed = get_preprocessed_outline(article_processed)
  1765. # print('article_processed')
  1766. article_processed = tableToText(article_processed)
  1767. article_processed = segment(article_processed)
  1768. article_processed = article_processed.replace('.','.') # 2021/12/01 修正OCR识别PDF小数点错误问题
  1769. article_processed = article_processed.replace('报价限价', '招标限价') #2021/12/17 由于报价限价预测为中投标金额所以修改
  1770. article_processed = article_processed.replace('成交工程价款', '成交工程价') # 2021/12/21 修正为中标价
  1771. # 修复OCR金额中“,”、“。”识别错误
  1772. article_processed_list = article_processed.split("##attachment##")
  1773. if len(article_processed_list)>1:
  1774. attachment_text = article_processed_list[1]
  1775. for _match in re.finditer("\d。\d{2}",attachment_text):
  1776. _match_text = _match.group()
  1777. attachment_text = attachment_text.replace(_match_text,_match_text.replace("。","."),1)
  1778. for _match in re.finditer("(\d,\d{3})[,,.]",attachment_text):
  1779. _match_text = _match.group()
  1780. attachment_text = attachment_text.replace(_match_text,_match_text.replace(",",","),1)
  1781. article_processed_list[1] = attachment_text
  1782. article_processed = "##attachment##".join(article_processed_list)
  1783. '''特别数据源对 预处理后文本 做特别修改'''
  1784. if web_source_no in ['03786-10', '00076-4', 'DX000105-2', '04080-3', '04080-4', '03761-3', '00695-7',"13740-2"]:
  1785. article_processed = special_treatment(article_processed, web_source_no)
  1786. # 提取bidway
  1787. list_bidway = extract_bidway(article_processed, _title)
  1788. if list_bidway:
  1789. bidway = list_bidway[0].get("body")
  1790. # bidway名称统一规范
  1791. bidway = bidway_integrate(bidway)
  1792. else:
  1793. bidway = ""
  1794. # 修正被","逗号分隔的时间
  1795. repair_time = re.compile("[12]\d,?\d,?\d,?[-—-―/年],?[0-1]?\d,?[-—-―/月],?[0-3]?\d,?[日号]?,?(?:上午|下午)?,?[0-2]?\d,?:,?[0-6]\d,?:,?[0-6]\d|"
  1796. "[12]\d,?\d,?\d,?[-—-―/年],?[0-1]?\d,?[-—-―/月],?[0-3]?\d,?[日号]?,?(?:上午|下午)?,?[0-2]?\d,?[:时点],?[0-6]\d分?|"
  1797. "[12]\d,?\d,?\d,?[-—-―/年],?[0-1]?\d,?[-—-―/月],?[0-3]?\d,?[日号]?,?(?:上午|下午)?,?[0-2]?\d,?[时点]|"
  1798. "[12]\d,?\d,?\d,?[-—-―/年],?[0-1]?\d,?[-—-―/月],?[0-3]?\d,?[日号]|"
  1799. "[0-2]?\d,?:,?[0-6]\d,?:,?[0-6]\d"
  1800. )
  1801. for _time in set(re.findall(repair_time,article_processed)):
  1802. if re.search(",",_time):
  1803. _time2 = re.sub(",", "", _time)
  1804. item = re.search("[12]\d{3}[-—-―/][0-1]?\d[-—-―/][0-3]\d(?=\d)", _time2)
  1805. if item:
  1806. _time2 = _time2.replace(item.group(),item.group() + " ")
  1807. article_processed = article_processed.replace(_time, _time2)
  1808. else:
  1809. item = re.search("[12]\d{3}[-—-―/][0-1]?\d[-—-―/][0-3]\d(?=\d)", _time)
  1810. if item:
  1811. _time2 = _time.replace(item.group(),item.group() + " ")
  1812. article_processed = article_processed.replace(_time, _time2)
  1813. # print('re_rtime',re.findall(repair_time,article_processed))
  1814. # log(article_processed)
  1815. if key_preprocess not in cost_time:
  1816. cost_time[key_preprocess] = 0
  1817. cost_time[key_preprocess] += round(time.time()-start_time,2)
  1818. #article_processed = article[1]
  1819. _article = Article(doc_id,article_processed,sourceContent,_send_doc_id,_title,
  1820. bidway=bidway)
  1821. _article.fingerprint = getFingerprint(_title+sourceContent)
  1822. _article.page_time = page_time
  1823. list_articles.append(_article)
  1824. return list_articles
  1825. def get_preprocessed_sentences(list_articles,useselffool=True,cost_time=dict()):
  1826. '''
  1827. :param list_articles: 经过预处理的article text
  1828. :return: list_sentences
  1829. '''
  1830. list_sentences = []
  1831. list_outlines = []
  1832. for article in list_articles:
  1833. list_sentences_temp = []
  1834. list_entitys_temp = []
  1835. doc_id = article.id
  1836. _send_doc_id = article.doc_id
  1837. _title = article.title
  1838. #表格处理
  1839. key_preprocess = "tableToText"
  1840. start_time = time.time()
  1841. article_processed = article.content
  1842. attachment_begin_index = -1
  1843. if key_preprocess not in cost_time:
  1844. cost_time[key_preprocess] = 0
  1845. cost_time[key_preprocess] += time.time()-start_time
  1846. #nlp处理
  1847. if article_processed is not None and len(article_processed)!=0:
  1848. split_patten = "。"
  1849. sentences = []
  1850. _begin = 0
  1851. sentences_set = set()
  1852. for _iter in re.finditer(split_patten,article_processed):
  1853. _sen = article_processed[_begin:_iter.span()[1]]
  1854. if len(_sen)>0 and _sen not in sentences_set:
  1855. # 标识在附件里的句子
  1856. if re.search("##attachment##",_sen):
  1857. attachment_begin_index = len(sentences)
  1858. # _sen = re.sub("##attachment##","",_sen)
  1859. sentences.append(_sen)
  1860. sentences_set.add(_sen)
  1861. _begin = _iter.span()[1]
  1862. _sen = article_processed[_begin:]
  1863. if re.search("##attachment##", _sen):
  1864. # _sen = re.sub("##attachment##", "", _sen)
  1865. attachment_begin_index = len(sentences)
  1866. if len(_sen)>0 and _sen not in sentences_set:
  1867. sentences.append(_sen)
  1868. sentences_set.add(_sen)
  1869. # 解析outline大纲分段
  1870. outline_list = []
  1871. if re.search("##split##",article.content):
  1872. temp_sentences = []
  1873. last_sentence_index = (-1,-1)
  1874. outline_index = 0
  1875. for sentence_index in range(len(sentences)):
  1876. sentence_text = sentences[sentence_index]
  1877. for _ in re.findall("##split##", sentence_text):
  1878. _match = re.search("##split##", sentence_text)
  1879. if last_sentence_index[0] > -1:
  1880. sentence_begin_index,wordOffset_begin = last_sentence_index
  1881. sentence_end_index = sentence_index
  1882. wordOffset_end = _match.start()
  1883. if sentence_begin_index<attachment_begin_index and sentence_end_index>=attachment_begin_index:
  1884. outline_list.append(Outline(doc_id,outline_index,'',sentence_begin_index,attachment_begin_index-1,wordOffset_begin,len(sentences[attachment_begin_index-1])))
  1885. else:
  1886. outline_list.append(Outline(doc_id,outline_index,'',sentence_begin_index,sentence_end_index,wordOffset_begin,wordOffset_end))
  1887. outline_index += 1
  1888. sentence_text = re.sub("##split##", "", sentence_text,count=1)
  1889. last_sentence_index = (sentence_index,_match.start())
  1890. temp_sentences.append(sentence_text)
  1891. if attachment_begin_index>-1 and last_sentence_index[0]<attachment_begin_index:
  1892. 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])))
  1893. else:
  1894. outline_list.append(Outline(doc_id,outline_index,'',last_sentence_index[0],len(sentences)-1,last_sentence_index[1],len(temp_sentences[-1])))
  1895. sentences = temp_sentences
  1896. #解析outline的outline_text内容
  1897. for _outline in outline_list:
  1898. if _outline.sentence_begin_index==_outline.sentence_end_index:
  1899. _text = sentences[_outline.sentence_begin_index][_outline.wordOffset_begin:_outline.wordOffset_end]
  1900. else:
  1901. _text = ""
  1902. for idx in range(_outline.sentence_begin_index,_outline.sentence_end_index+1):
  1903. if idx==_outline.sentence_begin_index:
  1904. _text += sentences[idx][_outline.wordOffset_begin:]
  1905. elif idx==_outline.sentence_end_index:
  1906. _text += sentences[idx][:_outline.wordOffset_end]
  1907. else:
  1908. _text += sentences[idx]
  1909. _outline.outline_text = _text
  1910. _outline_summary = re.split("[::,]",_text,1)[0]
  1911. if len(_outline_summary)<20:
  1912. _outline.outline_summary = _outline_summary
  1913. # print(_outline.outline_index,_outline.outline_text)
  1914. article.content = "".join(sentences)
  1915. # sentences.append(article_processed[_begin:])
  1916. lemmas = []
  1917. doc_offsets = []
  1918. dep_types = []
  1919. dep_tokens = []
  1920. time1 = time.time()
  1921. '''
  1922. tokens_all = fool.cut(sentences)
  1923. #pos_all = fool.LEXICAL_ANALYSER.pos(tokens_all)
  1924. #ner_tag_all = fool.LEXICAL_ANALYSER.ner_labels(sentences,tokens_all)
  1925. ner_entitys_all = fool.ner(sentences)
  1926. '''
  1927. #限流执行
  1928. key_nerToken = "nerToken"
  1929. start_time = time.time()
  1930. tokens_all = getTokens(sentences,useselffool=useselffool)
  1931. if key_nerToken not in cost_time:
  1932. cost_time[key_nerToken] = 0
  1933. cost_time[key_nerToken] += round(time.time()-start_time,2)
  1934. in_attachment = False
  1935. for sentence_index in range(len(sentences)):
  1936. if sentence_index == attachment_begin_index:
  1937. in_attachment = True
  1938. sentence_text = sentences[sentence_index]
  1939. tokens = tokens_all[sentence_index]
  1940. #pos_tag = pos_all[sentence_index]
  1941. pos_tag = ""
  1942. ner_entitys = ""
  1943. 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))
  1944. if len(list_sentences_temp)==0:
  1945. list_sentences_temp.append(Sentences(doc_id=doc_id,sentence_index=0,sentence_text="sentence_text",tokens=[],pos_tags=[],ner_tags=""))
  1946. list_sentences.append(list_sentences_temp)
  1947. list_outlines.append(outline_list)
  1948. return list_sentences,list_outlines
  1949. def get_preprocessed_entitys(list_sentences,useselffool=True,cost_time=dict()):
  1950. '''
  1951. :param list_sentences:分局情况
  1952. :param cost_time:
  1953. :return: list_entitys
  1954. '''
  1955. list_entitys = []
  1956. for list_sentence in list_sentences:
  1957. sentences = []
  1958. list_entitys_temp = []
  1959. for _sentence in list_sentence:
  1960. sentences.append(_sentence.sentence_text)
  1961. lemmas = []
  1962. doc_offsets = []
  1963. dep_types = []
  1964. dep_tokens = []
  1965. time1 = time.time()
  1966. '''
  1967. tokens_all = fool.cut(sentences)
  1968. #pos_all = fool.LEXICAL_ANALYSER.pos(tokens_all)
  1969. #ner_tag_all = fool.LEXICAL_ANALYSER.ner_labels(sentences,tokens_all)
  1970. ner_entitys_all = fool.ner(sentences)
  1971. '''
  1972. #限流执行
  1973. key_nerToken = "nerToken"
  1974. start_time = time.time()
  1975. found_yeji = 0 # 2021/8/6 增加判断是否正文包含评标结果 及类似业绩判断用于过滤后面的金额
  1976. # found_pingbiao = False
  1977. ner_entitys_all = getNers(sentences,useselffool=useselffool)
  1978. if key_nerToken not in cost_time:
  1979. cost_time[key_nerToken] = 0
  1980. cost_time[key_nerToken] += round(time.time()-start_time,2)
  1981. company_dict = set()
  1982. company_index = dict((i,set()) for i in range(len(list_sentence)))
  1983. for sentence_index in range(len(list_sentence)):
  1984. list_sentence_entitys = []
  1985. sentence_text = list_sentence[sentence_index].sentence_text
  1986. tokens = list_sentence[sentence_index].tokens
  1987. doc_id = list_sentence[sentence_index].doc_id
  1988. in_attachment = list_sentence[sentence_index].in_attachment
  1989. list_tokenbegin = []
  1990. begin = 0
  1991. for i in range(0,len(tokens)):
  1992. list_tokenbegin.append(begin)
  1993. begin += len(str(tokens[i]))
  1994. list_tokenbegin.append(begin+1)
  1995. #pos_tag = pos_all[sentence_index]
  1996. pos_tag = ""
  1997. ner_entitys = ner_entitys_all[sentence_index]
  1998. '''正则识别角色实体 经营部|经销部|电脑部|服务部|复印部|印刷部|彩印部|装饰部|修理部|汽修部|修理店|零售店|设计店|服务店|家具店|专卖店|分店|文具行|商行|印刷厂|修理厂|维修中心|修配中心|养护中心|服务中心|会馆|文化馆|超市|门市|商场|家具城|印刷社|经销处'''
  1999. for it in re.finditer(
  2000. '(?P<text_key_word>(((单一来源|中标|中选|中价|成交)(供应商|供货商|服务商|候选人|单位|人))|(供应商|供货商|服务商|候选人))(名称)?[为::]+)(?P<text>([^,。、;《::]{5,20})(厂|中心|超市|门市|商场|工作室|文印室|城|部|店|站|馆|行|社|处))[,。]',
  2001. sentence_text):
  2002. for k, v in it.groupdict().items():
  2003. if k == 'text_key_word':
  2004. keyword = v
  2005. if k == 'text':
  2006. entity = v
  2007. b = it.start() + len(keyword)
  2008. e = it.end() - 1
  2009. if (b, e, 'location', entity) in ner_entitys:
  2010. ner_entitys.remove((b, e, 'location', entity))
  2011. ner_entitys.append((b, e, 'company', entity))
  2012. elif (b, e, 'org', entity) not in ner_entitys and (b, e, 'company', entity) not in ner_entitys:
  2013. ner_entitys.append((b, e, 'company', entity))
  2014. for it in re.finditer(
  2015. '(?P<text_key_word>((建设|招租|招标|采购)(单位|人)|业主)(名称)?[为::]+)(?P<text>\w{2,4}[省市县区镇]([^,。、;《]{2,20})(管理处|办公室|委员会|村委会|纪念馆|监狱|管教所|修养所|社区|农场|林场|羊场|猪场|石场|村|幼儿园))[,。]',
  2016. sentence_text):
  2017. for k, v in it.groupdict().items():
  2018. if k == 'text_key_word':
  2019. keyword = v
  2020. if k == 'text':
  2021. entity = v
  2022. b = it.start() + len(keyword)
  2023. e = it.end() - 1
  2024. if (b, e, 'location', entity) in ner_entitys:
  2025. ner_entitys.remove((b, e, 'location', entity))
  2026. ner_entitys.append((b, e, 'org', entity))
  2027. if (b, e, 'org', entity) not in ner_entitys and (b, e, 'company', entity) not in ner_entitys:
  2028. ner_entitys.append((b, e, 'org', entity))
  2029. for ner_entity in ner_entitys:
  2030. if ner_entity[2] in ['company','org']:
  2031. company_dict.add((ner_entity[2],ner_entity[3]))
  2032. company_index[sentence_index].add((ner_entity[0],ner_entity[1]))
  2033. #识别package
  2034. #识别实体
  2035. for ner_entity in ner_entitys:
  2036. begin_index_temp = ner_entity[0]
  2037. end_index_temp = ner_entity[1]
  2038. entity_type = ner_entity[2]
  2039. entity_text = ner_entity[3]
  2040. if entity_type in ["org","company"] and not isLegalEnterprise(entity_text):
  2041. continue
  2042. for j in range(len(list_tokenbegin)):
  2043. if list_tokenbegin[j]==begin_index_temp:
  2044. begin_index = j
  2045. break
  2046. elif list_tokenbegin[j]>begin_index_temp:
  2047. begin_index = j-1
  2048. break
  2049. begin_index_temp += len(str(entity_text))
  2050. for j in range(begin_index,len(list_tokenbegin)):
  2051. if list_tokenbegin[j]>=begin_index_temp:
  2052. end_index = j-1
  2053. break
  2054. entity_id = "%s_%d_%d_%d"%(doc_id,sentence_index,begin_index,end_index)
  2055. #去掉标点符号
  2056. entity_text = re.sub("[,,。:!&@$\*]","",entity_text)
  2057. entity_text = entity_text.replace("(","(").replace(")",")") if isinstance(entity_text,str) else entity_text
  2058. 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))
  2059. # 标记文章末尾的"发布人”、“发布时间”实体
  2060. if sentence_index==len(list_sentence)-1:
  2061. if len(list_sentence_entitys[-2:])>2:
  2062. second2last = list_sentence_entitys[-2]
  2063. last = list_sentence_entitys[-1]
  2064. if (second2last.entity_type in ["company",'org'] and last.entity_type=="time") or (
  2065. second2last.entity_type=="time" and last.entity_type in ["company",'org']):
  2066. if last.wordOffset_begin - second2last.wordOffset_end < 6 and len(sentence_text) - last.wordOffset_end<6:
  2067. last.is_tail = True
  2068. second2last.is_tail = True
  2069. #使用正则识别金额
  2070. entity_type = "money"
  2071. #money_patten_str = "(([1-9][\d,,]*(?:\.\d+)?[百千万亿]?[\(\)()元整]+)|([零壹贰叁肆伍陆柒捌玖拾佰仟萬億十百千万亿元角分]{3,})|(?:[¥¥]+,?|报价|标价)[(\(]?([万])?元?[)\)]?[::]?.{,7}?([1-9][\d,,]*(?:\.\d+)?(?:,?)[百千万亿]?)|([1-9][\d,,]*(?:\.\d+)?(?:,?)[百千万亿]?)[\((]?([万元]{1,2}))*"
  2072. # list_money_pattern = {"cn":"(()()(?P<money_cn>[零壹贰叁肆伍陆柒捌玖拾佰仟萬億圆十百千万亿元角分]{3,})())",
  2073. # "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*[)\)]?))",
  2074. # "front_m":"((?P<text_front_m>(?:[(\(]?\s*(?P<unit_front_m_before>[万元]+)\s*[)\)])\s*[,,::]*(\s*[^壹贰叁肆伍陆柒捌玖拾佰仟萬億分万元]{,7}?))(?P<money_front_m>[0-9][\d,]*(?:\.\d+)?(?:,?)[百千万亿元]*)())",
  2075. # "behind_m":"(()()(?P<money_behind_m>[0-9][\d,,]*(?:\.\d+)?(?:,?)[百千万亿]*)[\((]?(?P<unit_behind_m>[万元]+(?P<filter_unit3>[台个只]*))[\))]?)"}
  2076. list_money_pattern = {"cn":"(()()(?P<money_cn>[零壹贰叁肆伍陆柒捌玖拾佰仟萬億圆十百千万亿元角分]{3,})())",
  2077. "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*[)\)]?))",
  2078. "front_m":"((?P<text_front_m>(?:[(\(]?\s*(?P<unit_front_m_before>[万亿]?元)\s*[)\)])\s*[,,::]*(\s*[^壹贰叁肆伍陆柒捌玖拾佰仟萬億分万元]{,7}?))(?P<money_front_m>[0-9][\d,]*(?:\.\d+)?(?:,?)[百千]*)())",
  2079. "behind_m":"(()()(?P<money_behind_m>[0-9][\d,]*(?:\.\d+)?(?:,?)[百千]*)(人民币)?[\((]?(?P<unit_behind_m>[万亿]?元(?P<filter_unit3>[台个只吨斤棵株页亩方条米]*))[\))]?)"}
  2080. # 2021/7/19 调整金额,单位提取正则,修复部分金额因为单位提取失败被过滤问题。
  2081. 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"]))
  2082. set_begin = set()
  2083. # for pattern_key in list_money_pattern.keys():
  2084. # for pattern_key in ["cn","key_word","behind_m","front_m"]:
  2085. # # pattern = re.compile(list_money_pattern[pattern_key])
  2086. # 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+)?(?:,?)[百千万亿元]*)())*")
  2087. # all_match = re.findall(pattern, sentence_text)
  2088. # index = 0
  2089. # for i in range(len(all_match)):
  2090. # if len(all_match[i][0])>0:
  2091. # print("===",all_match[i])
  2092. # #print(all_match[i][0])
  2093. # unit = ""
  2094. # entity_text = all_match[i][3]
  2095. # if pattern_key in ["key_word","front_m"]:
  2096. # unit = all_match[i][1]
  2097. # if pattern_key=="key_word":
  2098. # if all_match[i][1]=="" and all_match[i][4]!="":
  2099. # unit = all_match[i][4]
  2100. # else:
  2101. # unit = all_match[i][4]
  2102. # if entity_text.find("元")>=0:
  2103. # unit = ""
  2104. #
  2105. # index += len(all_match[i][0])-len(entity_text)-len(all_match[i][4])#-len(all_match[i][1])-len(all_match[i][2])#整个提出来的作为实体->数字部分作为整体,否则会丢失特征
  2106. # begin_index_temp = index
  2107. # for j in range(len(list_tokenbegin)):
  2108. # if list_tokenbegin[j]==index:
  2109. # begin_index = j
  2110. # break
  2111. # elif list_tokenbegin[j]>index:
  2112. # begin_index = j-1
  2113. # break
  2114. # index += len(str(entity_text))+len(all_match[i][4])#+len(all_match[i][2])+len(all_match[i][1])#整个提出来的作为实体
  2115. # end_index_temp = index
  2116. # #index += len(str(all_match[i][0]))
  2117. # for j in range(begin_index,len(list_tokenbegin)):
  2118. # if list_tokenbegin[j]>=index:
  2119. # end_index = j-1
  2120. # break
  2121. # entity_id = "%s_%d_%d_%d"%(doc_id,sentence_index,begin_index,end_index)
  2122. #
  2123. # entity_text = re.sub("[^0-9.零壹贰叁肆伍陆柒捌玖拾佰仟萬億十百千万亿元角分]","",entity_text)
  2124. # if len(unit)>0:
  2125. # entity_text = str(getUnifyMoney(entity_text)*getMultipleFactor(unit[0]))
  2126. # else:
  2127. # entity_text = str(getUnifyMoney(entity_text))
  2128. #
  2129. # _exists = False
  2130. # for item in list_sentence_entitys:
  2131. # if item.entity_id==entity_id and item.entity_type==entity_type:
  2132. # _exists = True
  2133. # if not _exists:
  2134. # if float(entity_text)>1:
  2135. # 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))
  2136. #
  2137. # else:
  2138. # index += 1
  2139. # if re.search('评标结果|候选人公示', sentence_text):
  2140. # found_pingbiao = True
  2141. if re.search('业绩', sentence_text):
  2142. found_yeji += 1
  2143. if found_yeji >= 2: # 过滤掉业绩后面的所有金额
  2144. all_match = []
  2145. else:
  2146. all_match = re.finditer(pattern_money, sentence_text)
  2147. index = 0
  2148. for _match in all_match:
  2149. if len(_match.group())>0:
  2150. # print("===",_match.group())
  2151. # # print(_match.groupdict())
  2152. notes = '' # 2021/7/20 新增备注金额大写或金额单位 if 金额大写 notes=大写 elif 单位 notes=单位
  2153. unit = ""
  2154. entity_text = ""
  2155. text_beforeMoney = ""
  2156. filter = ""
  2157. filter_unit = False
  2158. notSure = False
  2159. if re.search('业绩', sentence_text[:_match.span()[0]]): # 2021/7/21过滤掉业绩后面金额
  2160. # print('金额在业绩后面: ', _match.group(0))
  2161. found_yeji += 1
  2162. break
  2163. for k,v in _match.groupdict().items():
  2164. if v!="" and v is not None:
  2165. if k=='text_key_word':
  2166. notSure = True
  2167. if k.split("_")[0]=="money":
  2168. entity_text = v
  2169. if k.split("_")[0]=="unit":
  2170. unit = v
  2171. if k.split("_")[0]=="text":
  2172. text_beforeMoney = v
  2173. if k.split("_")[0]=="filter":
  2174. filter = v
  2175. if re.search("filter_unit",k) is not None:
  2176. filter_unit = True
  2177. # print(_match.group())
  2178. # print(entity_text,unit,text_beforeMoney,filter,filter_unit)
  2179. if re.search('(^\d{2,},\d{4,}万?$)|(^\d{2,},\d{2}万?$)', entity_text.strip()): # 2021/7/19 修正OCR识别小数点为逗号
  2180. if re.search('[幢栋号楼层]', sentence_text[max(0, _match.span()[0]-2):_match.span()[0]]):
  2181. entity_text = re.sub('\d+,', '', entity_text)
  2182. else:
  2183. entity_text = entity_text.replace(',', '.')
  2184. # print(' 修正OCR识别小数点为逗号')
  2185. if entity_text.find("元")>=0:
  2186. unit = ""
  2187. if unit == "": #2021/7/21 有明显金额特征的补充单位,避免被过滤
  2188. if ('¥' in text_beforeMoney or '¥' in text_beforeMoney):
  2189. unit = '元'
  2190. # print('明显金额特征补充单位 元')
  2191. elif re.search('[单报标限]价|金额|价格|(监理|设计|勘察)(服务)?费[::为]+$', text_beforeMoney.strip()) and \
  2192. re.search('\d{5,}',entity_text) and re.search('^0|1[3|4|5|6|7|8|9]\d{9}',entity_text)==None:
  2193. unit = '元'
  2194. # print('明显金额特征补充单位 元')
  2195. elif re.search('(^\d{,3}(,?\d{3})+(\.\d{2,7},?)$)|(^\d{,3}(,\d{3})+,?$)',entity_text):
  2196. unit = '元'
  2197. # print('明显金额特征补充单位 元')
  2198. if unit.find("万") >= 0 and entity_text.find("万") >= 0: #2021/7/19修改为金额文本有万,不计算单位
  2199. # print('修正金额及单位都有万, 金额:',entity_text, '单位:',unit)
  2200. unit = "元"
  2201. if re.search('.*万元万元', entity_text): #2021/7/19 修正两个万元
  2202. # print(' 修正两个万元',entity_text)
  2203. entity_text = entity_text.replace('万元万元','万元')
  2204. else:
  2205. if filter_unit:
  2206. continue
  2207. if filter!="":
  2208. continue
  2209. index = _match.span()[0]+len(text_beforeMoney)
  2210. begin_index_temp = index
  2211. for j in range(len(list_tokenbegin)):
  2212. if list_tokenbegin[j]==index:
  2213. begin_index = j
  2214. break
  2215. elif list_tokenbegin[j]>index:
  2216. begin_index = j-1
  2217. break
  2218. index = _match.span()[1]
  2219. end_index_temp = index
  2220. #index += len(str(all_match[i][0]))
  2221. for j in range(begin_index,len(list_tokenbegin)):
  2222. if list_tokenbegin[j]>=index:
  2223. end_index = j-1
  2224. break
  2225. entity_id = "%s_%d_%d_%d"%(doc_id,sentence_index,begin_index,end_index)
  2226. entity_text = re.sub("[^0-9.零壹贰叁肆伍陆柒捌玖拾佰仟萬億圆十百千万亿元角分]","",entity_text)
  2227. # print('转换前金额:', entity_text, '单位:', unit, '备注:',notes, 'text_beforeMoney:',text_beforeMoney)
  2228. if re.search('总投资|投资总额|总预算|总概算|投资规模', sentence_text[max(0, _match.span()[0] - 8):_match.span()[1]]): # 2021/8/5过滤掉总投资金额
  2229. # print('总投资金额: ', _match.group(0))
  2230. notes = '总投资'
  2231. elif re.search('投资', sentence_text[max(0, _match.span()[0] - 8):_match.span()[1]]): # 2021/11/18 投资金额不作为招标金额
  2232. notes = '投资'
  2233. elif re.search('工程造价', sentence_text[max(0, _match.span()[0] - 8):_match.span()[1]]): # 2021/12/20 工程造价不作为招标金额
  2234. notes = '工程造价'
  2235. elif (re.search('保证金', sentence_text[max(0, _match.span()[0] - 5):_match.span()[1]])
  2236. or re.search('保证金的?(缴纳)?(金额|金\?|额|\?)?[\((]*(万?元|为?人民币|大写|调整|变更|已?修改|更改|更正)?[\))]*[::为]',
  2237. sentence_text[max(0, _match.span()[0] - 10):_match.span()[1]])
  2238. or re.search('保证金由[\d.,]+.{,3}(变更|修改|更改|更正|调整?)为',
  2239. sentence_text[max(0, _match.span()[0] - 15):_match.span()[1]])):
  2240. notes = '保证金'
  2241. # print('保证金信息:', sentence_text[max(0, _match.span()[0] - 15):_match.span()[1]])
  2242. elif re.search('成本(警戒|预警)(线|价|值)[^0-9元]{,10}',
  2243. sentence_text[max(0, _match.span()[0] - 10):_match.span()[0]]):
  2244. notes = '成本警戒线'
  2245. elif re.search('(监理|设计|勘察)(服务)?费(报价)?[约为:]', sentence_text[_match.span()[0]:_match.span()[1]]):
  2246. cost_re = re.search('(监理|设计|勘察)(服务)?费', sentence_text[_match.span()[0]:_match.span()[1]])
  2247. notes = cost_re.group(1)
  2248. elif re.search('单价|总金额', sentence_text[_match.span()[0]:_match.span()[1]]):
  2249. notes = '单价'
  2250. elif re.search('[零壹贰叁肆伍陆柒捌玖拾佰仟萬億圆]', entity_text) != None:
  2251. notes = '大写'
  2252. if entity_text[0] == "拾": # 2021/12/16 修正大写金额省略了数字转换错误问题
  2253. entity_text = "壹"+entity_text
  2254. # print("补充备注:notes = 大写")
  2255. if len(unit)>0:
  2256. if unit.find('万')>=0 and len(entity_text.split('.')[0])>=8: # 2021/7/19 修正万元金额过大的情况
  2257. # print('修正单位万元金额过大的情况 金额:', entity_text, '单位:', unit)
  2258. entity_text = str(getUnifyMoney(entity_text) * getMultipleFactor(unit[0])/10000)
  2259. unit = '元' # 修正金额后单位 重置为元
  2260. else:
  2261. # print('str(getUnifyMoney(entity_text)*getMultipleFactor(unit[0])):')
  2262. entity_text = str(getUnifyMoney(entity_text)*getMultipleFactor(unit[0]))
  2263. else:
  2264. if entity_text.find('万')>=0 and entity_text.split('.')[0].isdigit() and len(entity_text.split('.')[0])>=8:
  2265. entity_text = str(getUnifyMoney(entity_text)/10000)
  2266. # print('修正金额字段含万 过大的情况')
  2267. else:
  2268. entity_text = str(getUnifyMoney(entity_text))
  2269. if float(entity_text)>100000000000 or float(entity_text)<100: # float(entity_text)<100 or 2022/3/4 取消最小金额限制
  2270. # print('过滤掉金额:float(entity_text)<100 or float(entity_text)>100000000000', entity_text, unit)
  2271. continue
  2272. if notSure and unit=="" and float(entity_text)>100*10000:
  2273. # print('过滤掉金额 notSure and unit=="" and float(entity_text)>100*10000:', entity_text, unit)
  2274. continue
  2275. _exists = False
  2276. for item in list_sentence_entitys:
  2277. if item.entity_id==entity_id and item.entity_type==entity_type:
  2278. _exists = True
  2279. if (begin_index >=item.begin_index and begin_index<=item.end_index) or (end_index>=item.begin_index and end_index<=item.end_index):
  2280. _exists = True
  2281. if not _exists:
  2282. if float(entity_text)>1:
  2283. 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))
  2284. list_sentence_entitys[-1].notes = notes # 2021/7/20 新增金额备注
  2285. list_sentence_entitys[-1].money_unit = unit # 2021/7/20 新增金额备注
  2286. # print('预处理中的 金额:%s, 单位:%s'%(entity_text,unit))
  2287. # print(entity_text,unit,notes)
  2288. else:
  2289. index += 1
  2290. # "联系人"正则补充提取 2021/11/15 新增
  2291. list_person_text = [entity.entity_text for entity in list_sentence_entitys if entity.entity_type=='person']
  2292. error_text = ['交易','机构','教育','项目','公司','中标','开标','截标','监督','政府','国家','中国','技术','投标','传真','网址','电子邮',
  2293. '联系','联系电','联系地','采购代','邮政编','邮政','电话','手机','手机号','联系人','地址','地点','邮箱','邮编','联系方','招标','招标人','代理',
  2294. '代理人','采购','附件','注意','登录','报名','踏勘',"测试"]
  2295. list_person_text = set(list_person_text + error_text)
  2296. re_person = re.compile("联系人[::]([\u4e00-\u9fa5]工)|"
  2297. "联系人[::]([\u4e00-\u9fa5]{2,3})(?=联系)|"
  2298. "联系人[::]([\u4e00-\u9fa5]{2,3})")
  2299. list_person = []
  2300. if not in_attachment:
  2301. for match_result in re_person.finditer(sentence_text):
  2302. match_text = match_result.group()
  2303. entity_text = match_text[4:]
  2304. wordOffset_begin = match_result.start() + 4
  2305. wordOffset_end = match_result.end()
  2306. # print(text[wordOffset_begin:wordOffset_end])
  2307. # 排除一些不为人名的实体
  2308. if re.search("^[\u4e00-\u9fa5]{7,}([,。]|$)",sentence_text[wordOffset_begin:wordOffset_begin+20]):
  2309. continue
  2310. if entity_text not in list_person_text and entity_text[:2] not in list_person_text:
  2311. _person = dict()
  2312. _person['body'] = entity_text
  2313. _person['begin_index'] = wordOffset_begin
  2314. _person['end_index'] = wordOffset_end
  2315. list_person.append(_person)
  2316. entity_type = "person"
  2317. for person in list_person:
  2318. begin_index_temp = person['begin_index']
  2319. for j in range(len(list_tokenbegin)):
  2320. if list_tokenbegin[j] == begin_index_temp:
  2321. begin_index = j
  2322. break
  2323. elif list_tokenbegin[j] > begin_index_temp:
  2324. begin_index = j - 1
  2325. break
  2326. index = person['end_index']
  2327. end_index_temp = index
  2328. for j in range(begin_index, len(list_tokenbegin)):
  2329. if list_tokenbegin[j] >= index:
  2330. end_index = j - 1
  2331. break
  2332. entity_id = "%s_%d_%d_%d" % (doc_id, sentence_index, begin_index, end_index)
  2333. entity_text = person['body']
  2334. list_sentence_entitys.append(
  2335. Entity(doc_id, entity_id, entity_text, entity_type, sentence_index, begin_index, end_index,
  2336. begin_index_temp, end_index_temp,in_attachment=in_attachment))
  2337. # 资金来源提取 2020/12/30 新增
  2338. list_moneySource = extract_moneySource(sentence_text)
  2339. entity_type = "moneysource"
  2340. for moneySource in list_moneySource:
  2341. begin_index_temp = moneySource['begin_index']
  2342. for j in range(len(list_tokenbegin)):
  2343. if list_tokenbegin[j] == begin_index_temp:
  2344. begin_index = j
  2345. break
  2346. elif list_tokenbegin[j] > begin_index_temp:
  2347. begin_index = j - 1
  2348. break
  2349. index = moneySource['end_index']
  2350. end_index_temp = index
  2351. for j in range(begin_index, len(list_tokenbegin)):
  2352. if list_tokenbegin[j] >= index:
  2353. end_index = j - 1
  2354. break
  2355. entity_id = "%s_%d_%d_%d" % (doc_id, sentence_index, begin_index, end_index)
  2356. entity_text = moneySource['body']
  2357. list_sentence_entitys.append(
  2358. Entity(doc_id, entity_id, entity_text, entity_type, sentence_index, begin_index, end_index,
  2359. begin_index_temp, end_index_temp,in_attachment=in_attachment))
  2360. # 电子邮箱提取 2021/11/04 新增
  2361. list_email = extract_email(sentence_text)
  2362. entity_type = "email" # 电子邮箱
  2363. for email in list_email:
  2364. begin_index_temp = email['begin_index']
  2365. for j in range(len(list_tokenbegin)):
  2366. if list_tokenbegin[j] == begin_index_temp:
  2367. begin_index = j
  2368. break
  2369. elif list_tokenbegin[j] > begin_index_temp:
  2370. begin_index = j - 1
  2371. break
  2372. index = email['end_index']
  2373. end_index_temp = index
  2374. for j in range(begin_index, len(list_tokenbegin)):
  2375. if list_tokenbegin[j] >= index:
  2376. end_index = j - 1
  2377. break
  2378. entity_id = "%s_%d_%d_%d" % (doc_id, sentence_index, begin_index, end_index)
  2379. entity_text = email['body']
  2380. list_sentence_entitys.append(
  2381. Entity(doc_id, entity_id, entity_text, entity_type, sentence_index, begin_index, end_index,
  2382. begin_index_temp, end_index_temp,in_attachment=in_attachment))
  2383. # 服务期限提取 2020/12/30 新增
  2384. list_servicetime = extract_servicetime(sentence_text)
  2385. entity_type = "serviceTime"
  2386. for servicetime in list_servicetime:
  2387. begin_index_temp = servicetime['begin_index']
  2388. for j in range(len(list_tokenbegin)):
  2389. if list_tokenbegin[j] == begin_index_temp:
  2390. begin_index = j
  2391. break
  2392. elif list_tokenbegin[j] > begin_index_temp:
  2393. begin_index = j - 1
  2394. break
  2395. index = servicetime['end_index']
  2396. end_index_temp = index
  2397. for j in range(begin_index, len(list_tokenbegin)):
  2398. if list_tokenbegin[j] >= index:
  2399. end_index = j - 1
  2400. break
  2401. entity_id = "%s_%d_%d_%d" % (doc_id, sentence_index, begin_index, end_index)
  2402. entity_text = servicetime['body']
  2403. list_sentence_entitys.append(
  2404. Entity(doc_id, entity_id, entity_text, entity_type, sentence_index, begin_index, end_index,
  2405. begin_index_temp, end_index_temp,in_attachment=in_attachment))
  2406. # 招标方式提取 2020/12/30 新增
  2407. # list_bidway = extract_bidway(sentence_text, )
  2408. # entity_type = "bidway"
  2409. # for bidway in list_bidway:
  2410. # begin_index_temp = bidway['begin_index']
  2411. # end_index_temp = bidway['end_index']
  2412. # begin_index = changeIndexFromWordToWords(tokens, begin_index_temp)
  2413. # end_index = changeIndexFromWordToWords(tokens, end_index_temp)
  2414. # if begin_index is None or end_index is None:
  2415. # continue
  2416. # print(begin_index_temp,end_index_temp,begin_index,end_index)
  2417. # entity_id = "%s_%d_%d_%d" % (doc_id, sentence_index, begin_index, end_index)
  2418. # entity_text = bidway['body']
  2419. # list_sentence_entitys.append(
  2420. # Entity(doc_id, entity_id, entity_text, entity_type, sentence_index, begin_index, end_index,
  2421. # begin_index_temp, end_index_temp))
  2422. # 2021/12/29 新增比率提取
  2423. list_ratio = extract_ratio(sentence_text)
  2424. entity_type = "ratio"
  2425. for ratio in list_ratio:
  2426. # print("ratio", ratio)
  2427. begin_index_temp = ratio['begin_index']
  2428. for j in range(len(list_tokenbegin)):
  2429. if list_tokenbegin[j] == begin_index_temp:
  2430. begin_index = j
  2431. break
  2432. elif list_tokenbegin[j] > begin_index_temp:
  2433. begin_index = j - 1
  2434. break
  2435. index = ratio['end_index']
  2436. end_index_temp = index
  2437. for j in range(begin_index, len(list_tokenbegin)):
  2438. if list_tokenbegin[j] >= index:
  2439. end_index = j - 1
  2440. break
  2441. entity_id = "%s_%d_%d_%d" % (doc_id, sentence_index, begin_index, end_index)
  2442. entity_text = ratio['body']
  2443. list_sentence_entitys.append(
  2444. Entity(doc_id, entity_id, entity_text, entity_type, sentence_index, begin_index, end_index,
  2445. begin_index_temp, end_index_temp,in_attachment=in_attachment))
  2446. list_sentence_entitys.sort(key=lambda x:x.begin_index)
  2447. list_entitys_temp = list_entitys_temp+list_sentence_entitys
  2448. # 补充ner模型未识别全的company/org实体
  2449. for sentence_index in range(len(list_sentence)):
  2450. sentence_text = list_sentence[sentence_index].sentence_text
  2451. tokens = list_sentence[sentence_index].tokens
  2452. doc_id = list_sentence[sentence_index].doc_id
  2453. in_attachment = list_sentence[sentence_index].in_attachment
  2454. list_tokenbegin = []
  2455. begin = 0
  2456. for i in range(0, len(tokens)):
  2457. list_tokenbegin.append(begin)
  2458. begin += len(str(tokens[i]))
  2459. list_tokenbegin.append(begin + 1)
  2460. add_sentence_entitys = []
  2461. company_dict = sorted(list(company_dict),key=lambda x:len(x[1]),reverse=True)
  2462. for company_type,company_text in company_dict:
  2463. begin_index_list = findAllIndex(company_text,sentence_text)
  2464. for begin_index in begin_index_list:
  2465. is_continue = False
  2466. for t_begin,t_end in list(company_index[sentence_index]):
  2467. if begin_index>=t_begin and begin_index+len(company_text)<=t_end:
  2468. is_continue = True
  2469. break
  2470. if not is_continue:
  2471. add_sentence_entitys.append((begin_index,begin_index+len(company_text),company_type,company_text))
  2472. company_index[sentence_index].add((begin_index,begin_index+len(company_text)))
  2473. else:
  2474. continue
  2475. for ner_entity in add_sentence_entitys:
  2476. begin_index_temp = ner_entity[0]
  2477. end_index_temp = ner_entity[1]
  2478. entity_type = ner_entity[2]
  2479. entity_text = ner_entity[3]
  2480. if entity_type in ["org","company"] and not isLegalEnterprise(entity_text):
  2481. continue
  2482. for j in range(len(list_tokenbegin)):
  2483. if list_tokenbegin[j]==begin_index_temp:
  2484. begin_index = j
  2485. break
  2486. elif list_tokenbegin[j]>begin_index_temp:
  2487. begin_index = j-1
  2488. break
  2489. begin_index_temp += len(str(entity_text))
  2490. for j in range(begin_index,len(list_tokenbegin)):
  2491. if list_tokenbegin[j]>=begin_index_temp:
  2492. end_index = j-1
  2493. break
  2494. entity_id = "%s_%d_%d_%d"%(doc_id,sentence_index,begin_index,end_index)
  2495. #去掉标点符号
  2496. entity_text = re.sub("[,,。:!&@$\*]","",entity_text)
  2497. entity_text = entity_text.replace("(","(").replace(")",")") if isinstance(entity_text,str) else entity_text
  2498. 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))
  2499. list_entitys_temp.sort(key=lambda x:(x.sentence_index,x.begin_index))
  2500. list_entitys.append(list_entitys_temp)
  2501. return list_entitys
  2502. def union_result(codeName,prem):
  2503. '''
  2504. @summary:模型的结果拼成字典
  2505. @param:
  2506. codeName:编号名称模型的结果字典
  2507. prem:拿到属性的角色的字典
  2508. @return:拼接起来的字典
  2509. '''
  2510. result = []
  2511. assert len(codeName)==len(prem)
  2512. for item_code,item_prem in zip(codeName,prem):
  2513. result.append(dict(item_code,**item_prem))
  2514. return result
  2515. def persistenceData(data):
  2516. '''
  2517. @summary:将中间结果保存到数据库-线上生产的时候不需要执行
  2518. '''
  2519. import psycopg2
  2520. conn = psycopg2.connect(dbname="BiddingKG",user="postgres",password="postgres",host="192.168.2.101")
  2521. cursor = conn.cursor()
  2522. for item_index in range(len(data)):
  2523. item = data[item_index]
  2524. doc_id = item[0]
  2525. dic = item[1]
  2526. code = dic['code']
  2527. name = dic['name']
  2528. prem = dic['prem']
  2529. if len(code)==0:
  2530. code_insert = ""
  2531. else:
  2532. code_insert = ";".join(code)
  2533. prem_insert = ""
  2534. for item in prem:
  2535. for x in item:
  2536. if isinstance(x, list):
  2537. if len(x)>0:
  2538. for x1 in x:
  2539. prem_insert+="/".join(x1)+","
  2540. prem_insert+="$"
  2541. else:
  2542. prem_insert+=str(x)+"$"
  2543. prem_insert+=";"
  2544. sql = " insert into predict_validation(doc_id,code,name,prem) values('"+doc_id+"','"+code_insert+"','"+name+"','"+prem_insert+"')"
  2545. cursor.execute(sql)
  2546. conn.commit()
  2547. conn.close()
  2548. def persistenceData1(list_entitys,list_sentences):
  2549. '''
  2550. @summary:将中间结果保存到数据库-线上生产的时候不需要执行
  2551. '''
  2552. import psycopg2
  2553. conn = psycopg2.connect(dbname="BiddingKG",user="postgres",password="postgres",host="192.168.2.101")
  2554. cursor = conn.cursor()
  2555. for list_entity in list_entitys:
  2556. for entity in list_entity:
  2557. if entity.values is not None:
  2558. 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)+")"
  2559. else:
  2560. 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)+")"
  2561. cursor.execute(sql)
  2562. for list_sentence in list_sentences:
  2563. for sentence in list_sentence:
  2564. str_tokens = "["
  2565. for item in sentence.tokens:
  2566. str_tokens += "'"
  2567. if item=="'":
  2568. str_tokens += "''"
  2569. else:
  2570. str_tokens += item
  2571. str_tokens += "',"
  2572. str_tokens = str_tokens[:-1]+"]"
  2573. sql = " insert into predict_sentences(doc_id,sentence_index,tokens) values('"+sentence.doc_id+"',"+str(sentence.sentence_index)+",array"+str_tokens+")"
  2574. cursor.execute(sql)
  2575. conn.commit()
  2576. conn.close()
  2577. def _handle(item,result_queue):
  2578. dochtml = item["dochtml"]
  2579. docid = item["docid"]
  2580. list_innerTable = tableToText(BeautifulSoup(dochtml,"lxml"))
  2581. flag = False
  2582. if list_innerTable:
  2583. flag = True
  2584. for table in list_innerTable:
  2585. result_queue.put({"docid":docid,"json_table":json.dumps(table,ensure_ascii=False)})
  2586. def getPredictTable():
  2587. filename = "D:\Workspace2016\DataExport\data\websouce_doc.csv"
  2588. import pandas as pd
  2589. import json
  2590. from BiddingKG.dl.common.MultiHandler import MultiHandler,Queue
  2591. df = pd.read_csv(filename)
  2592. df_data = {"json_table":[],"docid":[]}
  2593. _count = 0
  2594. _sum = len(df["docid"])
  2595. task_queue = Queue()
  2596. result_queue = Queue()
  2597. _index = 0
  2598. for dochtml,docid in zip(df["dochtmlcon"],df["docid"]):
  2599. task_queue.put({"docid":docid,"dochtml":dochtml,"json_table":None})
  2600. _index += 1
  2601. mh = MultiHandler(task_queue=task_queue,task_handler=_handle,result_queue=result_queue,process_count=5,thread_count=1)
  2602. mh.run()
  2603. while True:
  2604. try:
  2605. item = result_queue.get(block=True,timeout=1)
  2606. df_data["docid"].append(item["docid"])
  2607. df_data["json_table"].append(item["json_table"])
  2608. except Exception as e:
  2609. print(e)
  2610. break
  2611. df_1 = pd.DataFrame(df_data)
  2612. df_1.to_csv("../form/websource_67000_table.csv",columns=["docid","json_table"])
  2613. if __name__=="__main__":
  2614. '''
  2615. import glob
  2616. for file in glob.glob("C:\\Users\\User\\Desktop\\test\\*.html"):
  2617. file_txt = str(file).replace("html","txt")
  2618. with codecs.open(file_txt,"a+",encoding="utf8") as f:
  2619. f.write("\n================\n")
  2620. content = codecs.open(file,"r",encoding="utf8").read()
  2621. f.write(segment(tableToText(BeautifulSoup(content,"lxml"))))
  2622. '''
  2623. # content = codecs.open("C:\\Users\\User\\Desktop\\2.html","r",encoding="utf8").read()
  2624. # print(segment(tableToText(BeautifulSoup(content,"lxml"))))
  2625. # getPredictTable()
  2626. with open('D:/138786703.html', 'r', encoding='utf-8') as f:
  2627. sourceContent = f.read()
  2628. # article_processed = segment(tableToText(BeautifulSoup(sourceContent, "lxml")))
  2629. # print(article_processed)
  2630. list_articles, list_sentences, list_entitys, _cost_time = get_preprocessed([['doc_id', sourceContent, "", "", '', '2021-02-01']], useselffool=True)
  2631. for entity in list_entitys[0]:
  2632. print(entity.entity_type, entity.entity_text)