Preprocessing.py 159 KB

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