Preprocessing.py 144 KB

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