Preprocessing.py 163 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182
  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. string_list = [re.sub("\s+","",i)for i in tbody.strings if i and i!='\n']
  974. tbody.string = ",".join(string_list)
  975. table_max_len = 30000
  976. tbody.string = tbody.string[:table_max_len]
  977. tbody.name = "turntable"
  978. return None
  979. # fixSpan(tbody)
  980. # inner_table = getTable(tbody)
  981. # inner_table = fixTable(inner_table)
  982. table2list = TableTag2List()
  983. inner_table = table2list.table2list(tbody, segment)
  984. inner_table = fixTable(inner_table)
  985. if inner_table == []:
  986. string_list = [re.sub("\s+", "", i) for i in tbody.strings if i and i != '\n']
  987. tbody.string = ",".join(string_list)
  988. table_max_len = 30000
  989. tbody.string = tbody.string[:table_max_len]
  990. # log('异常表格直接取全文')
  991. tbody.name = "turntable"
  992. return None
  993. if len(inner_table)>0 and len(inner_table[0])>0:
  994. for tr in inner_table:
  995. for td in tr:
  996. if isinstance(td, str):
  997. tbody.string = segment(tbody,final=False)
  998. table_max_len = 30000
  999. tbody.string = tbody.string[:table_max_len]
  1000. # log('异常表格,不做表格处理,直接取全文')
  1001. tbody.name = "turntable"
  1002. return None
  1003. #inner_table,head_list = setHead_withRule(inner_table,pat_head,pat_value,3)
  1004. #inner_table,head_list = setHead_inline(inner_table)
  1005. # inner_table, head_list = setHead_initem(inner_table,pat_head)
  1006. inner_table, head_list = set_head_model(inner_table)
  1007. # inner_table,head_list = setHead_incontext(inner_table,pat_head)
  1008. # print("table_head", inner_table)
  1009. # print("head_list", head_list)
  1010. # for begin in range(len(head_list[:-1])):
  1011. # for item in inner_table[head_list[begin]:head_list[begin+1]]:
  1012. # print(item)
  1013. # print("====")
  1014. removeFix(inner_table)
  1015. # print("----")
  1016. # print(head_list)
  1017. # for item in inner_table:
  1018. # print(item)
  1019. tbody.string = getTableText(inner_table,head_list)
  1020. table_max_len = 30000
  1021. tbody.string = tbody.string[:table_max_len]
  1022. # print(tbody.string)
  1023. tbody.name = "turntable"
  1024. return inner_table
  1025. return None
  1026. pat_head = re.compile('^(名称|序号|项目|标项|工程|品目[一二三四1234]|第[一二三四1234](标段|名|候选人|中标)|包段|标包|分包|包号|货物|单位|数量|价格|报价|金额|总价|单价|[招投中]标|候选|编号|得分|评委|评分|名次|排名|排序|科室|方式|工期|时间|产品|开始|结束|联系|日期|面积|姓名|证号|备注|级别|地[点址]|类型|代理|制造|企业资质|质量目标|工期目标|(需求|服务|项目|施工|采购|招租|出租|转让|出让|业主|询价|委托|权属|招标|竞得|抽取|承建)(人|方|单位)(名称)?|(供应商|供货商|服务商)(名称)?)$')
  1027. #pat_head = re.compile('(名称|序号|项目|工程|品目[一二三四1234]|第[一二三四1234](标段|候选人|中标)|包段|包号|货物|单位|数量|价格|报价|金额|总价|单价|[招投中]标|供应商|候选|编号|得分|评委|评分|名次|排名|排序|科室|方式|工期|时间|产品|开始|结束|联系|日期|面积|姓名|证号|备注|级别|地[点址]|类型|代理)')
  1028. pat_value = re.compile("(\d{2,}.\d{1}|\d+年\d+月|\d{8,}|\d{3,}-\d{6,}|有限[责任]*公司|^\d+$)")
  1029. list_innerTable = []
  1030. # 2022/2/9 删除干扰标签
  1031. for tag in soup.find_all('option'): #例子: 216661412
  1032. if 'selected' not in tag.attrs:
  1033. tag.extract()
  1034. for ul in soup.find_all('ul'): #例子 156439663 多个不同channel 类别的标题
  1035. if ul.find_all('li') == ul.findChildren(recursive=False) and len(set(re.findall(
  1036. '招标公告|中标结果公示|中标候选人公示|招标答疑|开标评标|合同履?约?公示|资格评审',
  1037. ul.get_text(), re.S)))>3:
  1038. ul.extract()
  1039. # tbodies = soup.find_all('table')
  1040. # 遍历表格中的每个tbody
  1041. tbodies = []
  1042. in_attachment = False
  1043. for _part in soup.find_all():
  1044. if _part.name=='table':
  1045. tbodies.append((_part,in_attachment))
  1046. elif _part.name=='div':
  1047. if 'class' in _part.attrs and "richTextFetch" in _part['class']:
  1048. in_attachment = True
  1049. #逆序处理嵌套表格
  1050. for tbody_index in range(1,len(tbodies)+1):
  1051. tbody,_in_attachment = tbodies[len(tbodies)-tbody_index]
  1052. inner_table = trunTable(tbody,_in_attachment)
  1053. list_innerTable.append(inner_table)
  1054. # tbodies = soup.find_all('tbody')
  1055. # 遍历表格中的每个tbody
  1056. tbodies = []
  1057. in_attachment = False
  1058. for _part in soup.find_all():
  1059. if _part.name == 'tbody':
  1060. tbodies.append((_part, in_attachment))
  1061. elif _part.name == 'div':
  1062. if 'class' in _part.attrs and "richTextFetch" in _part['class']:
  1063. in_attachment = True
  1064. #逆序处理嵌套表格
  1065. for tbody_index in range(1,len(tbodies)+1):
  1066. tbody,_in_attachment = tbodies[len(tbodies)-tbody_index]
  1067. inner_table = trunTable(tbody,_in_attachment)
  1068. list_innerTable.append(inner_table)
  1069. return soup
  1070. # return list_innerTable
  1071. re_num = re.compile("[二三四五六七八九]十[一二三四五六七八九]?|十[一二三四五六七八九]|[一二三四五六七八九十]")
  1072. num_dict = {
  1073. "一": 1, "二": 2,
  1074. "三": 3, "四": 4,
  1075. "五": 5, "六": 6,
  1076. "七": 7, "八": 8,
  1077. "九": 9, "十": 10}
  1078. # 一百以内的中文大写转换为数字
  1079. def change2num(text):
  1080. result_num = -1
  1081. # text = text[:6]
  1082. match = re_num.search(text)
  1083. if match:
  1084. _num = match.group()
  1085. if num_dict.get(_num):
  1086. return num_dict.get(_num)
  1087. else:
  1088. tenths = 1
  1089. the_unit = 0
  1090. num_split = _num.split("十")
  1091. if num_dict.get(num_split[0]):
  1092. tenths = num_dict.get(num_split[0])
  1093. if num_dict.get(num_split[1]):
  1094. the_unit = num_dict.get(num_split[1])
  1095. result_num = tenths * 10 + the_unit
  1096. elif re.search("\d{1,2}",text):
  1097. _num = re.search("\d{1,2}",text).group()
  1098. result_num = int(_num)
  1099. return result_num
  1100. #大纲分段处理
  1101. def get_preprocessed_outline(soup):
  1102. pattern_0 = re.compile("^(?:[二三四五六七八九]十[一二三四五六七八九]?|十[一二三四五六七八九]|[一二三四五六七八九十])[、.\.]")
  1103. pattern_1 = re.compile("^[\((]?(?:[二三四五六七八九]十[一二三四五六七八九]?|十[一二三四五六七八九]|[一二三四五六七八九十])[\))]")
  1104. pattern_2 = re.compile("^\d{1,2}[、.\.](?=[^\d]{1,2}|$)")
  1105. pattern_3 = re.compile("^[\((]?\d{1,2}[\))]")
  1106. pattern_list = [pattern_0, pattern_1, pattern_2, pattern_3]
  1107. body = soup.find("body")
  1108. if body == None:
  1109. return soup # 修复 无body的报错 例子:264419050
  1110. body_child = body.find_all(recursive=False)
  1111. deal_part = body
  1112. # print(body_child[0]['id'])
  1113. if 'id' in body_child[0].attrs:
  1114. if len(body_child) <= 2 and body_child[0]['id'] == 'pcontent':
  1115. deal_part = body_child[0]
  1116. if len(deal_part.find_all(recursive=False))>2:
  1117. deal_part = deal_part.parent
  1118. skip_tag = ['turntable', 'tbody', 'th', 'tr', 'td', 'table','thead','tfoot']
  1119. for part in deal_part.find_all(recursive=False):
  1120. # 查找解析文本的主干部分
  1121. is_main_text = False
  1122. through_text_num = 0
  1123. while (not is_main_text and part.find_all(recursive=False)):
  1124. while len(part.find_all(recursive=False)) == 1 and part.get_text(strip=True) == \
  1125. part.find_all(recursive=False)[0].get_text(strip=True):
  1126. part = part.find_all(recursive=False)[0]
  1127. max_len = len(part.get_text(strip=True))
  1128. is_main_text = True
  1129. for t_part in part.find_all(recursive=False):
  1130. if t_part.name not in skip_tag and t_part.get_text(strip=True)!="":
  1131. through_text_num += 1
  1132. if t_part.get_text(strip=True)!="" and len(t_part.get_text(strip=True))/max_len>=0.65:
  1133. if t_part.name not in skip_tag:
  1134. is_main_text = False
  1135. part = t_part
  1136. break
  1137. else:
  1138. while len(t_part.find_all(recursive=False)) == 1 and t_part.get_text(strip=True) == \
  1139. t_part.find_all(recursive=False)[0].get_text(strip=True):
  1140. t_part = t_part.find_all(recursive=False)[0]
  1141. if through_text_num>2:
  1142. is_table = True
  1143. for _t_part in t_part.find_all(recursive=False):
  1144. if _t_part.name not in skip_tag:
  1145. is_table = False
  1146. break
  1147. if not is_table:
  1148. is_main_text = False
  1149. part = t_part
  1150. break
  1151. else:
  1152. is_main_text = False
  1153. part = t_part
  1154. break
  1155. is_find = False
  1156. for _pattern in pattern_list:
  1157. last_index = 0
  1158. handle_list = []
  1159. for _part in part.find_all(recursive=False):
  1160. if _part.name not in skip_tag and _part.get_text(strip=True) != "":
  1161. # print('text:', _part.get_text(strip=True))
  1162. re_match = re.search(_pattern, _part.get_text(strip=True))
  1163. if re_match:
  1164. outline_index = change2num(re_match.group())
  1165. if last_index < outline_index:
  1166. # _part.insert_before("##split##")
  1167. handle_list.append(_part)
  1168. last_index = outline_index
  1169. if len(handle_list)>1:
  1170. is_find = True
  1171. for _part in handle_list:
  1172. _part.insert_before("##split##")
  1173. if is_find:
  1174. break
  1175. # print(soup)
  1176. return soup
  1177. #数据清洗
  1178. def segment(soup,final=True):
  1179. # print("==")
  1180. # print(soup)
  1181. # print("====")
  1182. #segList = ["tr","div","h1", "h2", "h3", "h4", "h5", "h6", "header"]
  1183. subspaceList = ["td",'a',"span","p"]
  1184. if soup.name in subspaceList:
  1185. #判断有值叶子节点数
  1186. _count = 0
  1187. for child in soup.find_all(recursive=True):
  1188. if child.get_text().strip()!="" and len(child.find_all())==0:
  1189. _count += 1
  1190. if _count<=1:
  1191. text = soup.get_text()
  1192. # 2020/11/24 大网站规则添加
  1193. if 'title' in soup.attrs:
  1194. if '...' in soup.get_text() and soup.get_text().strip()[:-3] in soup.attrs['title']:
  1195. text = soup.attrs['title']
  1196. _list = []
  1197. for x in re.split("\s+",text):
  1198. if x.strip()!="":
  1199. _list.append(len(x))
  1200. if len(_list)>0:
  1201. _minLength = min(_list)
  1202. if _minLength>2:
  1203. _substr = ","
  1204. else:
  1205. _substr = ""
  1206. else:
  1207. _substr = ""
  1208. text = text.replace("\r\n",",").replace("\n",",")
  1209. text = re.sub("\s+",_substr,text)
  1210. # text = re.sub("\s+","##space##",text)
  1211. return text
  1212. segList = ["title"]
  1213. commaList = ["div","br","td","p","li"]
  1214. #commaList = []
  1215. spaceList = ["span"]
  1216. tbodies = soup.find_all('tbody')
  1217. if len(tbodies) == 0:
  1218. tbodies = soup.find_all('table')
  1219. # 递归遍历所有节点,插入符号
  1220. for child in soup.find_all(recursive=True):
  1221. # print(child.name,child.get_text())
  1222. if child.name in segList:
  1223. child.insert_after("。")
  1224. if child.name in commaList:
  1225. child.insert_after(",")
  1226. # if child.name == 'div' and 'class' in child.attrs:
  1227. # # 添加附件"attachment"标识
  1228. # if "richTextFetch" in child['class']:
  1229. # child.insert_before("##attachment##")
  1230. # print(child.parent)
  1231. # if child.name in subspaceList:
  1232. # child.insert_before("#subs"+str(child.name)+"#")
  1233. # child.insert_after("#sube"+str(child.name)+"#")
  1234. # if child.name in spaceList:
  1235. # child.insert_after(" ")
  1236. text = str(soup.get_text())
  1237. #替换英文冒号为中文冒号
  1238. text = re.sub("(?<=[\u4e00-\u9fa5]):|:(?=[\u4e00-\u9fa5])",":",text)
  1239. #替换为中文逗号
  1240. text = re.sub("(?<=[\u4e00-\u9fa5]),|,(?=[\u4e00-\u9fa5])",",",text)
  1241. #替换为中文分号
  1242. text = re.sub("(?<=[\u4e00-\u9fa5]);|;(?=[\u4e00-\u9fa5])",";",text)
  1243. # 感叹号替换为中文句号
  1244. text = re.sub("(?<=[\u4e00-\u9fa5])[!!]|[!!](?=[\u4e00-\u9fa5])","。",text)
  1245. #替换格式未识别的问号为" " ,update:2021/7/20
  1246. text = re.sub("[?\?]{2,}|\n"," ",text)
  1247. #替换"""为"“",否则导入deepdive出错
  1248. # text = text.replace('"',"“").replace("\r","").replace("\n",",")
  1249. text = text.replace('"',"“").replace("\r","").replace("\n","").replace("\\n","") #2022/1/4修复 非分段\n 替换为逗号造成 公司拆分 span \n南航\n上海\n分公司
  1250. # print('==1',text)
  1251. # text = re.sub("\s{4,}",",",text)
  1252. # 解决公告中的" "空格替换问题
  1253. if re.search("\s{4,}",text):
  1254. _text = ""
  1255. for _sent in re.split("。+",text):
  1256. for _sent2 in re.split(',+',_sent):
  1257. for _sent3 in re.split(":+",_sent2):
  1258. for _t in re.split("\s{4,}",_sent3):
  1259. if len(_t)<3:
  1260. _text += _t
  1261. else:
  1262. _text += ","+_t
  1263. _text += ":"
  1264. _text = _text[:-1]
  1265. _text += ","
  1266. _text = _text[:-1]
  1267. _text += "。"
  1268. _text = _text[:-1]
  1269. text = _text
  1270. # print('==2',text)
  1271. #替换标点
  1272. #替换连续的标点
  1273. if final:
  1274. text = re.sub("##space##"," ",text)
  1275. punc_pattern = "(?P<del>[。,;::,\s]+)"
  1276. list_punc = re.findall(punc_pattern,text)
  1277. list_punc.sort(key=lambda x:len(x),reverse=True)
  1278. for punc_del in list_punc:
  1279. if len(punc_del)>1:
  1280. if len(punc_del.strip())>0:
  1281. if ":" in punc_del.strip():
  1282. if "。" in punc_del.strip():
  1283. text = re.sub(punc_del, ":。", text)
  1284. else:
  1285. text = re.sub(punc_del,":",text)
  1286. else:
  1287. text = re.sub(punc_del,punc_del.strip()[0],text) #2021/12/09 修正由于某些标签后插入符号把原来符号替换
  1288. else:
  1289. text = re.sub(punc_del,"",text)
  1290. #将连续的中文句号替换为一个
  1291. text_split = text.split("。")
  1292. text_split = [x for x in text_split if len(x)>0]
  1293. text = "。".join(text_split)
  1294. # #删除标签中的所有空格
  1295. # for subs in subspaceList:
  1296. # patten = "#subs"+str(subs)+"#(.*?)#sube"+str(subs)+"#"
  1297. # while(True):
  1298. # oneMatch = re.search(re.compile(patten),text)
  1299. # if oneMatch is not None:
  1300. # _match = oneMatch.group(1)
  1301. # text = text.replace("#subs"+str(subs)+"#"+_match+"#sube"+str(subs)+"#",_match)
  1302. # else:
  1303. # break
  1304. # text过大报错
  1305. LOOP_LEN = 10000
  1306. LOOP_BEGIN = 0
  1307. _text = ""
  1308. if len(text)<10000000:
  1309. while(LOOP_BEGIN<len(text)):
  1310. _text += re.sub(")",")",re.sub("(","(",re.sub("\s+","",text[LOOP_BEGIN:LOOP_BEGIN+LOOP_LEN])))
  1311. LOOP_BEGIN += LOOP_LEN
  1312. text = _text
  1313. # 附件标识前修改为句号,避免正文和附件内容混合在一起
  1314. text = re.sub("[^。](?=##attachment##)","。",text)
  1315. text = re.sub("[^。](?=##attachment_begin##)","。",text)
  1316. text = re.sub("[^。](?=##attachment_end##)","。",text)
  1317. text = re.sub("##attachment_begin##。","##attachment_begin##",text)
  1318. text = re.sub("##attachment_end##。","##attachment_end##",text)
  1319. return text
  1320. '''
  1321. #数据清洗
  1322. def segment(soup):
  1323. segList = ["title"]
  1324. commaList = ["p","div","h1", "h2", "h3", "h4", "h5", "h6", "header", "dl", "ul", "label"]
  1325. spaceList = ["span"]
  1326. tbodies = soup.find_all('tbody')
  1327. if len(tbodies) == 0:
  1328. tbodies = soup.find_all('table')
  1329. # 递归遍历所有节点,插入符号
  1330. for child in soup.find_all(recursive=True):
  1331. if child.name == 'br':
  1332. child.insert_before(',')
  1333. child_text = re.sub('\s', '', child.get_text())
  1334. if child_text == '' or child_text[-1] in ['。',',',':',';']:
  1335. continue
  1336. if child.name in segList:
  1337. child.insert_after("。")
  1338. if child.name in commaList:
  1339. if len(child_text)>3 and len(child_text) <50: # 先判断是否字数少于50,成立加逗号,否则加句号
  1340. child.insert_after(",")
  1341. elif len(child_text) >=50:
  1342. child.insert_after("。")
  1343. #if child.name in spaceList:
  1344. #child.insert_after(" ")
  1345. text = str(soup.get_text())
  1346. text = re.sub("\s{5,}",",",text)
  1347. text = text.replace('"',"“").replace("\r","").replace("\n",",")
  1348. #替换"""为"“",否则导入deepdive出错
  1349. text = text.replace('"',"“")
  1350. #text = text.replace('"',"“").replace("\r","").replace("\n","")
  1351. #删除所有空格
  1352. text = re.sub("\s+","#nbsp#",text)
  1353. text_list = text.split('#nbsp#')
  1354. new_text = ''
  1355. for i in range(len(text_list)-1):
  1356. if text_list[i] == '' or text_list[i][-1] in [',','。',';',':']:
  1357. new_text += text_list[i]
  1358. elif re.findall('([一二三四五六七八九]、)', text_list[i+1][:4]) != []:
  1359. new_text += text_list[i] + '。'
  1360. elif re.findall('([0-9]、)', text_list[i+1][:4]) != []:
  1361. new_text += text_list[i] + ';'
  1362. elif text_list[i].isdigit() and text_list[i+1].isdigit():
  1363. new_text += text_list[i] + ' '
  1364. elif text_list[i][-1] in ['-',':','(',')','/','(',')','——','年','月','日','时','分','¥'] or text_list[i+1][0] in ['-',':','(',')','/','(',')','——','年','月','日','时','分','元','万元']:
  1365. new_text += text_list[i]
  1366. elif len(text_list[i]) >= 3 and len(text_list[i+1]) >= 3:
  1367. new_text += text_list[i] + ','
  1368. else:
  1369. new_text += text_list[i]
  1370. new_text += text_list[-1]
  1371. text = new_text
  1372. #替换英文冒号为中文冒号
  1373. text = re.sub("(?<=[\u4e00-\u9fa5]):|:(?=[\u4e00-\u9fa5])",":",text)
  1374. #替换为中文逗号
  1375. text = re.sub("(?<=[\u4e00-\u9fa5]),|,(?=[\u4e00-\u9fa5])",",",text)
  1376. #替换为中文分号
  1377. text = re.sub("(?<=[\u4e00-\u9fa5]);|;(?=[\u4e00-\u9fa5])",";",text)
  1378. #替换标点
  1379. while(True):
  1380. #替换连续的标点
  1381. punc = re.search(",(?P<punc>:|。|,|;)\s*",text)
  1382. if punc is not None:
  1383. text = re.sub(","+punc.group("punc")+"\s*",punc.group("punc"),text)
  1384. punc = re.search("(?P<punc>:|。|,|;)\s*,",text)
  1385. if punc is not None:
  1386. text = re.sub(punc.group("punc")+"\s*,",punc.group("punc"),text)
  1387. else:
  1388. #替换标点之后的空格
  1389. punc = re.search("(?P<punc>:|。|,|;)\s+",text)
  1390. if punc is not None:
  1391. text = re.sub(punc.group("punc")+"\s+",punc.group("punc"),text)
  1392. else:
  1393. break
  1394. #将连续的中文句号替换为一个
  1395. text_split = text.split("。")
  1396. text_split = [x for x in text_split if len(x)>0]
  1397. text = "。".join(text_split)
  1398. #替换中文括号为英文括号
  1399. text = re.sub("(","(",text)
  1400. text = re.sub(")",")",text)
  1401. return text
  1402. '''
  1403. #连续实体合并(弃用)
  1404. def union_ner(list_ner):
  1405. result_list = []
  1406. union_index = []
  1407. union_index_set = set()
  1408. for i in range(len(list_ner)-1):
  1409. if len(set([str(list_ner[i][2]),str(list_ner[i+1][2])])&set(["org","company"]))==2:
  1410. if list_ner[i][1]-list_ner[i+1][0]==1:
  1411. union_index_set.add(i)
  1412. union_index_set.add(i+1)
  1413. union_index.append((i,i+1))
  1414. for i in range(len(list_ner)):
  1415. if i not in union_index_set:
  1416. result_list.append(list_ner[i])
  1417. for item in union_index:
  1418. #print(str(list_ner[item[0]][3])+str(list_ner[item[1]][3]))
  1419. 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])))
  1420. return result_list
  1421. # def get_preprocessed(articles,useselffool=False):
  1422. # '''
  1423. # @summary:预处理步骤,NLP处理、实体识别
  1424. # @param:
  1425. # articles:待处理的文章list [[id,source,jointime,doc_id,title]]
  1426. # @return:list of articles,list of each article of sentences,list of each article of entitys
  1427. # '''
  1428. # list_articles = []
  1429. # list_sentences = []
  1430. # list_entitys = []
  1431. # cost_time = dict()
  1432. # for article in articles:
  1433. # list_sentences_temp = []
  1434. # list_entitys_temp = []
  1435. # doc_id = article[0]
  1436. # sourceContent = article[1]
  1437. # _send_doc_id = article[3]
  1438. # _title = article[4]
  1439. # #表格处理
  1440. # key_preprocess = "tableToText"
  1441. # start_time = time.time()
  1442. # article_processed = segment(tableToText(BeautifulSoup(sourceContent,"lxml")))
  1443. #
  1444. # # log(article_processed)
  1445. #
  1446. # if key_preprocess not in cost_time:
  1447. # cost_time[key_preprocess] = 0
  1448. # cost_time[key_preprocess] += time.time()-start_time
  1449. #
  1450. # #article_processed = article[1]
  1451. # list_articles.append(Article(doc_id,article_processed,sourceContent,_send_doc_id,_title))
  1452. # #nlp处理
  1453. # if article_processed is not None and len(article_processed)!=0:
  1454. # split_patten = "。"
  1455. # sentences = []
  1456. # _begin = 0
  1457. # for _iter in re.finditer(split_patten,article_processed):
  1458. # sentences.append(article_processed[_begin:_iter.span()[1]])
  1459. # _begin = _iter.span()[1]
  1460. # sentences.append(article_processed[_begin:])
  1461. #
  1462. # lemmas = []
  1463. # doc_offsets = []
  1464. # dep_types = []
  1465. # dep_tokens = []
  1466. #
  1467. # time1 = time.time()
  1468. #
  1469. # '''
  1470. # tokens_all = fool.cut(sentences)
  1471. # #pos_all = fool.LEXICAL_ANALYSER.pos(tokens_all)
  1472. # #ner_tag_all = fool.LEXICAL_ANALYSER.ner_labels(sentences,tokens_all)
  1473. # ner_entitys_all = fool.ner(sentences)
  1474. # '''
  1475. # #限流执行
  1476. # key_nerToken = "nerToken"
  1477. # start_time = time.time()
  1478. # tokens_all,ner_entitys_all = getTokensAndNers(sentences,useselffool=useselffool)
  1479. # if key_nerToken not in cost_time:
  1480. # cost_time[key_nerToken] = 0
  1481. # cost_time[key_nerToken] += time.time()-start_time
  1482. #
  1483. #
  1484. # for sentence_index in range(len(sentences)):
  1485. #
  1486. #
  1487. #
  1488. # list_sentence_entitys = []
  1489. # sentence_text = sentences[sentence_index]
  1490. # tokens = tokens_all[sentence_index]
  1491. #
  1492. # list_tokenbegin = []
  1493. # begin = 0
  1494. # for i in range(0,len(tokens)):
  1495. # list_tokenbegin.append(begin)
  1496. # begin += len(str(tokens[i]))
  1497. # list_tokenbegin.append(begin+1)
  1498. # #pos_tag = pos_all[sentence_index]
  1499. # pos_tag = ""
  1500. #
  1501. # ner_entitys = ner_entitys_all[sentence_index]
  1502. #
  1503. # 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))
  1504. #
  1505. # #识别package
  1506. #
  1507. #
  1508. # #识别实体
  1509. # for ner_entity in ner_entitys:
  1510. # begin_index_temp = ner_entity[0]
  1511. # end_index_temp = ner_entity[1]
  1512. # entity_type = ner_entity[2]
  1513. # entity_text = ner_entity[3]
  1514. #
  1515. # for j in range(len(list_tokenbegin)):
  1516. # if list_tokenbegin[j]==begin_index_temp:
  1517. # begin_index = j
  1518. # break
  1519. # elif list_tokenbegin[j]>begin_index_temp:
  1520. # begin_index = j-1
  1521. # break
  1522. # begin_index_temp += len(str(entity_text))
  1523. # for j in range(begin_index,len(list_tokenbegin)):
  1524. # if list_tokenbegin[j]>=begin_index_temp:
  1525. # end_index = j-1
  1526. # break
  1527. # entity_id = "%s_%d_%d_%d"%(doc_id,sentence_index,begin_index,end_index)
  1528. #
  1529. # #去掉标点符号
  1530. # entity_text = re.sub("[,,。:]","",entity_text)
  1531. # 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))
  1532. #
  1533. #
  1534. # #使用正则识别金额
  1535. # entity_type = "money"
  1536. #
  1537. # #money_patten_str = "(([1-9][\d,,]*(?:\.\d+)?[百千万亿]?[\(\)()元整]+)|([零壹贰叁肆伍陆柒捌玖拾佰仟萬億十百千万亿元角分]{3,})|(?:[¥¥]+,?|报价|标价)[(\(]?([万])?元?[)\)]?[::]?.{,7}?([1-9][\d,,]*(?:\.\d+)?(?:,?)[百千万亿]?)|([1-9][\d,,]*(?:\.\d+)?(?:,?)[百千万亿]?)[\((]?([万元]{1,2}))*"
  1538. #
  1539. # list_money_pattern = {"cn":"(()()([零壹贰叁肆伍陆柒捌玖拾佰仟萬億十百千万亿元角分]{3,})())*",
  1540. # "key_word":"((?:[¥¥]+,?|[报标限]价|金额)(?:[(\(]?\s*([万元]*)\s*[)\)]?)\s*[::]?(\s*[^壹贰叁肆伍陆柒捌玖拾佰仟萬億分]{,7}?)([0-9][\d,,]*(?:\.\d+)?(?:,?)[百千万亿元]*)())*",
  1541. # "front_m":"((?:[(\(]?\s*([万元]+)\s*[)\)])\s*[::]?(\s*[^壹贰叁肆伍陆柒捌玖拾佰仟萬億分]{,7}?)([0-9][\d,,]*(?:\.\d+)?(?:,?)[百千万亿元]*)())*",
  1542. # "behind_m":"(()()([0-9][\d,,]*(?:\.\d+)?(?:,?)[百千万亿]*)[\((]?([万元]+)[\))]?)*"}
  1543. #
  1544. # set_begin = set()
  1545. # for pattern_key in list_money_pattern.keys():
  1546. # pattern = re.compile(list_money_pattern[pattern_key])
  1547. # all_match = re.findall(pattern, sentence_text)
  1548. # index = 0
  1549. # for i in range(len(all_match)):
  1550. # if len(all_match[i][0])>0:
  1551. # # print("===",all_match[i])
  1552. # #print(all_match[i][0])
  1553. # unit = ""
  1554. # entity_text = all_match[i][3]
  1555. # if pattern_key in ["key_word","front_m"]:
  1556. # unit = all_match[i][1]
  1557. # else:
  1558. # unit = all_match[i][4]
  1559. # if entity_text.find("元")>=0:
  1560. # unit = ""
  1561. #
  1562. # index += len(all_match[i][0])-len(entity_text)-len(all_match[i][4])#-len(all_match[i][1])-len(all_match[i][2])#整个提出来的作为实体->数字部分作为整体,否则会丢失特征
  1563. #
  1564. # begin_index_temp = index
  1565. # for j in range(len(list_tokenbegin)):
  1566. # if list_tokenbegin[j]==index:
  1567. # begin_index = j
  1568. # break
  1569. # elif list_tokenbegin[j]>index:
  1570. # begin_index = j-1
  1571. # break
  1572. # index += len(str(entity_text))+len(all_match[i][4])#+len(all_match[i][2])+len(all_match[i][1])#整个提出来的作为实体
  1573. # end_index_temp = index
  1574. # #index += len(str(all_match[i][0]))
  1575. # for j in range(begin_index,len(list_tokenbegin)):
  1576. # if list_tokenbegin[j]>=index:
  1577. # end_index = j-1
  1578. # break
  1579. # entity_id = "%s_%d_%d_%d"%(doc_id,sentence_index,begin_index,end_index)
  1580. #
  1581. #
  1582. # entity_text = re.sub("[^0-9.零壹贰叁肆伍陆柒捌玖拾佰仟萬億十百千万亿元角分]","",entity_text)
  1583. # if len(unit)>0:
  1584. # entity_text = str(getUnifyMoney(entity_text)*getMultipleFactor(unit[0]))
  1585. # else:
  1586. # entity_text = str(getUnifyMoney(entity_text))
  1587. #
  1588. # _exists = False
  1589. # for item in list_sentence_entitys:
  1590. # if item.entity_id==entity_id and item.entity_type==entity_type:
  1591. # _exists = True
  1592. # if not _exists:
  1593. # if float(entity_text)>10:
  1594. # 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))
  1595. #
  1596. # else:
  1597. # index += 1
  1598. #
  1599. # list_sentence_entitys.sort(key=lambda x:x.begin_index)
  1600. # list_entitys_temp = list_entitys_temp+list_sentence_entitys
  1601. # list_sentences.append(list_sentences_temp)
  1602. # list_entitys.append(list_entitys_temp)
  1603. # return list_articles,list_sentences,list_entitys,cost_time
  1604. def get_preprocessed(articles, useselffool=False):
  1605. '''
  1606. @summary:预处理步骤,NLP处理、实体识别
  1607. @param:
  1608. articles:待处理的文章list [[id,source,jointime,doc_id,title]]
  1609. @return:list of articles,list of each article of sentences,list of each article of entitys
  1610. '''
  1611. cost_time = dict()
  1612. list_articles = get_preprocessed_article(articles,cost_time)
  1613. list_sentences,list_outlines = get_preprocessed_sentences(list_articles,True,cost_time)
  1614. list_entitys = get_preprocessed_entitys(list_sentences,True,cost_time)
  1615. calibrateEnterprise(list_articles,list_sentences,list_entitys)
  1616. return list_articles,list_sentences,list_entitys,list_outlines,cost_time
  1617. def special_treatment(sourceContent, web_source_no):
  1618. try:
  1619. if web_source_no == 'DX000202-1':
  1620. ser = re.search('中标供应商及中标金额:【(([\w()]{5,20}-[\d,.]+,)+)】', sourceContent)
  1621. if ser:
  1622. new = ""
  1623. l = ser.group(1).split(',')
  1624. for i in range(len(l)):
  1625. it = l[i]
  1626. if '-' in it:
  1627. role, money = it.split('-')
  1628. new += '标段%d, 中标供应商: ' % (i + 1) + role + ',中标金额:' + money + '。'
  1629. sourceContent = sourceContent.replace(ser.group(0), new, 1)
  1630. elif web_source_no == '00753-14':
  1631. body = sourceContent.find("body")
  1632. body_child = body.find_all(recursive=False)
  1633. pcontent = body
  1634. if 'id' in body_child[0].attrs:
  1635. if len(body_child) <= 2 and body_child[0]['id'] == 'pcontent':
  1636. pcontent = body_child[0]
  1637. # pcontent = sourceContent.find("div", id="pcontent")
  1638. pcontent = pcontent.find_all(recursive=False)[0]
  1639. first_table = None
  1640. for idx in range(len(pcontent.find_all(recursive=False))):
  1641. t_part = pcontent.find_all(recursive=False)[idx]
  1642. if t_part.name != "table":
  1643. break
  1644. if idx == 0:
  1645. first_table = t_part
  1646. else:
  1647. for _tr in t_part.find("tbody").find_all(recursive=False):
  1648. first_table.find("tbody").append(_tr)
  1649. t_part.clear()
  1650. elif web_source_no == 'DX008357-11':
  1651. body = sourceContent.find("body")
  1652. body_child = body.find_all(recursive=False)
  1653. pcontent = body
  1654. if 'id' in body_child[0].attrs:
  1655. if len(body_child) <= 2 and body_child[0]['id'] == 'pcontent':
  1656. pcontent = body_child[0]
  1657. # pcontent = sourceContent.find("div", id="pcontent")
  1658. pcontent = pcontent.find_all(recursive=False)[0]
  1659. error_table = []
  1660. is_error_table = False
  1661. for part in pcontent.find_all(recursive=False):
  1662. if is_error_table:
  1663. if part.name == "table":
  1664. error_table.append(part)
  1665. else:
  1666. break
  1667. if part.name == "div" and part.get_text(strip=True) == "中标候选单位:":
  1668. is_error_table = True
  1669. first_table = None
  1670. for idx in range(len(error_table)):
  1671. t_part = error_table[idx]
  1672. # if t_part.name != "table":
  1673. # break
  1674. if idx == 0:
  1675. for _tr in t_part.find("tbody").find_all(recursive=False):
  1676. if _tr.get_text(strip=True) == "":
  1677. _tr.decompose()
  1678. first_table = t_part
  1679. else:
  1680. for _tr in t_part.find("tbody").find_all(recursive=False):
  1681. if _tr.get_text(strip=True) != "":
  1682. first_table.find("tbody").append(_tr)
  1683. t_part.clear()
  1684. elif web_source_no == '18021-2':
  1685. body = sourceContent.find("body")
  1686. body_child = body.find_all(recursive=False)
  1687. pcontent = body
  1688. if 'id' in body_child[0].attrs:
  1689. if len(body_child) <= 2 and body_child[0]['id'] == 'pcontent':
  1690. pcontent = body_child[0]
  1691. # pcontent = sourceContent.find("div", id="pcontent")
  1692. td = pcontent.find_all("td")
  1693. for _td in td:
  1694. if str(_td.string).strip() == "报价金额":
  1695. _td.string = "单价"
  1696. elif web_source_no == '13740-2':
  1697. # “xxx成为成交供应商”
  1698. re_match = re.search("[^,。]+成为[^,。]*成交供应商", sourceContent)
  1699. if re_match:
  1700. sourceContent = sourceContent.replace(re_match.group(), "成交人:" + re_match.group())
  1701. elif web_source_no == '03786-10':
  1702. ser1 = re.search('中标价:([\d,.]+)', sourceContent)
  1703. ser2 = re.search('合同金额[((]万元[))]:([\d,.]+)', sourceContent)
  1704. if ser1 and ser2:
  1705. m1 = ser1.group(1).replace(',', '')
  1706. m2 = ser2.group(1).replace(',', '')
  1707. if float(m1) < 100000 and (m1.split('.')[0] == m2.split('.')[0] or m2 == '0'):
  1708. new = '中标价(万元):' + m1
  1709. sourceContent = sourceContent.replace(ser1.group(0), new, 1)
  1710. elif web_source_no=='00076-4':
  1711. ser = re.search('主要标的数量:([0-9一]+)\w{,3},主要标的单价:([\d,.]+)元?,合同金额:(.00),', sourceContent)
  1712. if ser:
  1713. num = ser.group(1).replace('一', '1')
  1714. try:
  1715. num = 1 if num == '0' else num
  1716. unit_price = ser.group(2).replace(',', '')
  1717. total_price = str(int(num) * float(unit_price))
  1718. new = '合同金额:' + total_price
  1719. sourceContent = sourceContent.replace('合同金额:.00', new, 1)
  1720. except Exception as e:
  1721. log('preprocessing.py special_treatment exception')
  1722. elif web_source_no=='DX000105-2':
  1723. if re.search("成交公示", sourceContent) and re.search(',投标人:', sourceContent) and re.search(',成交人:', sourceContent)==None:
  1724. sourceContent = sourceContent.replace(',投标人:', ',成交人:')
  1725. elif web_source_no in ['03795-1', '03795-2']:
  1726. if re.search('中标单位如下', sourceContent) and re.search(',投标人:', sourceContent) and re.search(',中标人:', sourceContent)==None:
  1727. sourceContent = sourceContent.replace(',投标人:', ',中标人:')
  1728. elif web_source_no in ['04080-3', '04080-4']:
  1729. ser = re.search('合同金额:([0-9,]+.[0-9]{3,})(.{,4})', sourceContent)
  1730. if ser and '万' not in ser.group(2):
  1731. sourceContent = sourceContent.replace('合同金额:', '合同金额(万元):')
  1732. elif web_source_no=='03761-3':
  1733. ser = re.search('中标价,([0-9]+)[.0-9]*%', sourceContent)
  1734. if ser and int(ser.group(1))>100:
  1735. sourceContent = sourceContent.replace(ser.group(0), ser.group(0)[:-1]+'元')
  1736. elif web_source_no=='00695-7':
  1737. ser = re.search('支付金额:', sourceContent)
  1738. if ser:
  1739. sourceContent = sourceContent.replace('支付金额:', '合同金额:')
  1740. elif web_source_no=='00811-8':
  1741. if re.search('是否中标:是', sourceContent) and re.search('排名:\d,', sourceContent):
  1742. sourceContent = re.sub('排名:\d,', '候选', sourceContent)
  1743. return sourceContent
  1744. except Exception as e:
  1745. log('特殊数据源: %s 预处理特别修改抛出异常: %s'%(web_source_no, e))
  1746. return sourceContent
  1747. def article_limit(soup,limit_words=30000):
  1748. sub_space = re.compile("\s+")
  1749. def soup_limit(_soup,_count,max_count=30000,max_gap=500):
  1750. """
  1751. :param _soup: soup
  1752. :param _count: 当前字数
  1753. :param max_count: 字数最大限制
  1754. :param max_gap: 超过限制后的最大误差
  1755. :return:
  1756. """
  1757. _gap = _count - max_count
  1758. _is_skip = False
  1759. next_soup = None
  1760. while len(_soup.find_all(recursive=False)) == 1 and \
  1761. _soup.get_text(strip=True) == _soup.find_all(recursive=False)[0].get_text(strip=True):
  1762. _soup = _soup.find_all(recursive=False)[0]
  1763. if len(_soup.find_all(recursive=False)) == 0:
  1764. _soup.string = str(_soup.get_text())[:max_count-_count]
  1765. _count += len(re.sub(sub_space, "", _soup.string))
  1766. _gap = _count - max_count
  1767. next_soup = None
  1768. else:
  1769. for _soup_part in _soup.find_all(recursive=False):
  1770. if not _is_skip:
  1771. _count += len(re.sub(sub_space, "", _soup_part.get_text()))
  1772. if _count >= max_count:
  1773. _gap = _count - max_count
  1774. if _gap <= max_gap:
  1775. _is_skip = True
  1776. else:
  1777. _is_skip = True
  1778. next_soup = _soup_part
  1779. _count -= len(re.sub(sub_space, "", _soup_part.get_text()))
  1780. continue
  1781. else:
  1782. _soup_part.decompose()
  1783. return _count,_gap,next_soup
  1784. text_count = 0
  1785. have_attachment = False
  1786. attachment_part = None
  1787. for child in soup.find_all(recursive=True):
  1788. if child.name == 'div' and 'class' in child.attrs:
  1789. if "richTextFetch" in child['class']:
  1790. child.insert_before("##attachment##。") # 句号分开,避免项目名称等提取
  1791. attachment_part = child
  1792. have_attachment = True
  1793. break
  1794. if not have_attachment:
  1795. # 无附件
  1796. if len(re.sub(sub_space, "", soup.get_text())) > limit_words:
  1797. text_count,gap,n_soup = soup_limit(soup,text_count,max_count=limit_words,max_gap=500)
  1798. while n_soup:
  1799. text_count, gap, n_soup = soup_limit(n_soup, text_count, max_count=limit_words, max_gap=500)
  1800. else:
  1801. # 有附件
  1802. _text = re.sub(sub_space, "", soup.get_text())
  1803. _text_split = _text.split("##attachment##")
  1804. if len(_text_split[0])>limit_words:
  1805. main_soup = attachment_part.parent
  1806. main_text = main_soup.find_all(recursive=False)[0]
  1807. text_count, gap, n_soup = soup_limit(main_text, text_count, max_count=limit_words, max_gap=500)
  1808. while n_soup:
  1809. text_count, gap, n_soup = soup_limit(n_soup, text_count, max_count=limit_words, max_gap=500)
  1810. if len(_text_split[1])>limit_words:
  1811. # attachment_html纯文本,无子结构
  1812. if len(attachment_part.find_all(recursive=False))==0:
  1813. attachment_part.string = str(attachment_part.get_text())[:limit_words]
  1814. else:
  1815. attachment_text_nums = 0
  1816. attachment_skip = False
  1817. for part in attachment_part.find_all(recursive=False):
  1818. if not attachment_skip:
  1819. last_attachment_text_nums = attachment_text_nums
  1820. attachment_text_nums = attachment_text_nums + len(re.sub(sub_space, "", part.get_text()))
  1821. if attachment_text_nums>=limit_words:
  1822. part.string = str(part.get_text())[:limit_words-last_attachment_text_nums]
  1823. attachment_skip = True
  1824. else:
  1825. part.decompose()
  1826. return soup
  1827. def attachment_filelink(soup):
  1828. have_attachment = False
  1829. attachment_part = None
  1830. for child in soup.find_all(recursive=True):
  1831. if child.name == 'div' and 'class' in child.attrs:
  1832. if "richTextFetch" in child['class']:
  1833. attachment_part = child
  1834. have_attachment = True
  1835. break
  1836. if not have_attachment:
  1837. return soup
  1838. else:
  1839. # 附件类型:图片、表格
  1840. attachment_type = re.compile("\.(?:png|jpg|jpeg|tif|bmp|xlsx|xls)$")
  1841. attachment_dict = dict()
  1842. for _attachment in attachment_part.find_all(recursive=False):
  1843. if _attachment.name == 'div' and 'filemd5' in _attachment.attrs:
  1844. # print('filemd5',_attachment['filemd5'])
  1845. attachment_dict[_attachment['filemd5']] = _attachment
  1846. # print(attachment_dict)
  1847. for child in soup.find_all(recursive=True):
  1848. if child.name == 'div' and 'class' in child.attrs:
  1849. if "richTextFetch" in child['class']:
  1850. break
  1851. if "filelink" in child.attrs and child['filelink'] in attachment_dict:
  1852. if re.search(attachment_type,str(child.string).strip()) or \
  1853. ('original' in child.attrs and re.search(attachment_type,str(child['original']).strip())) or \
  1854. ('href' in child.attrs and re.search(attachment_type,str(child['href']).strip())):
  1855. # 附件插入正文标识
  1856. child.insert_before("。##attachment_begin##")
  1857. child.insert_after("。##attachment_end##")
  1858. child.replace_with(attachment_dict[child['filelink']])
  1859. # print('格式化输出',soup.prettify())
  1860. return soup
  1861. def del_achievement(text):
  1862. if re.search('中标|成交|入围|结果|评标|开标|候选人', text[:500]) == None or re.search('业绩', text) == None:
  1863. return text
  1864. p0 = '[,。;]((\d{1,2})|\d{1,2}、)[\w、]{,8}:|((\d{1,2})|\d{1,2}、)|。' # 例子 264392818
  1865. p1 = '业绩[:,](\d、[-\w()、]{6,30}(工程|项目|勘察|设计|施工|监理|总承包|采购|更新)[\w()]{,10}[,;])+' # 例子 257717618
  1866. p2 = '(类似业绩情况:|业绩:)(\w{,20}:)?(((\d)|\d、)项目名称:[-\w(),;、\d\s:]{5,100}[;。])+' # 例子 264345826
  1867. p3 = '(投标|类似|(类似)?项目|合格|有效|企业|工程)?业绩(名称|信息|\d)?:(项目名称:)?[-\w()、]{6,50}(项目|工程|勘察|设计|施工|监理|总承包|采购|更新)'
  1868. l = []
  1869. tmp = []
  1870. for it in re.finditer(p0, text):
  1871. if it.group(0)[-3:] in ['业绩:', '荣誉:']:
  1872. if tmp != []:
  1873. del_text = text[tmp[0]:it.start()]
  1874. l.append(del_text)
  1875. tmp = []
  1876. tmp.append(it.start())
  1877. elif tmp != []:
  1878. del_text = text[tmp[0]:it.start()]
  1879. l.append(del_text)
  1880. tmp = []
  1881. if tmp != []:
  1882. del_text = text[tmp[0]:]
  1883. l.append(del_text)
  1884. for del_text in l:
  1885. text = text.replace(del_text, '')
  1886. # print('删除业绩信息:', del_text)
  1887. for rs in re.finditer(p1, text):
  1888. # print('删除业绩信息:', rs.group(0))
  1889. text = text.replace(rs.group(0), '')
  1890. for rs in re.finditer(p2, text):
  1891. # print('删除业绩信息:', rs.group(0))
  1892. text = text.replace(rs.group(0), '')
  1893. for rs in re.finditer(p3, text):
  1894. # print('删除业绩信息:', rs.group(0))
  1895. text = text.replace(rs.group(0), '')
  1896. return text
  1897. def del_tabel_achievement(soup):
  1898. if re.search('中标|成交|入围|结果|评标|开标|候选人', soup.text[:800]) == None or re.search('业绩', soup.text)==None:
  1899. return None
  1900. p1 = '中标(单位|候选人)的?(企业|项目|项目负责人|\w{,5})?业绩|类似(项目)?业绩|\w{,10}业绩$|业绩(公示|情况|荣誉)'
  1901. '''删除前面标签 命中业绩规则;当前标签为表格且公布业绩相关信息的去除'''
  1902. for tag in soup.find_all('table'):
  1903. pre_text = tag.findPreviousSibling().text.strip() if tag.findPreviousSibling() != None else ""
  1904. tr_text = tag.find('tr').text.strip() if tag.find('tr') != None else ""
  1905. # print(re.search(p1, pre_text),pre_text, len(pre_text), re.findall('序号|中标候选人名称|项目名称|工程名称|合同金额|建设单位|业主', tr_text))
  1906. if re.search(p1, pre_text) and len(pre_text) < 20 and tag.find('tr') != None and len(tr_text)<100:
  1907. _count = 0
  1908. for td in tag.find('tr').find_all('td'):
  1909. td_text = td.text.strip()
  1910. if len(td_text) > 25:
  1911. break
  1912. if len(td_text) < 25 and re.search('中标候选人|(项目|业绩|工程)名称|\w{,10}业绩$|合同金额|建设单位|采购单位|业主|甲方', td_text):
  1913. _count += 1
  1914. if _count >=2:
  1915. pre_tag = tag.findPreviousSibling().extract()
  1916. del_tag = tag.extract()
  1917. # print('删除表格业绩内容', pre_tag.text + del_tag.text)
  1918. break
  1919. elif re.search('业绩名称', tr_text) and re.search('建设单位|采购单位|业主', tr_text) and len(tr_text)<100:
  1920. del_tag = tag.extract()
  1921. # print('删除表格业绩内容', del_tag.text)
  1922. del_trs = []
  1923. '''删除表格某些行公布的业绩信息'''
  1924. for tag in soup.find_all('table'):
  1925. text = tag.text
  1926. if re.search('业绩', text) == None:
  1927. continue
  1928. # for tr in tag.find_all('tr'):
  1929. trs = tag.find_all('tr')
  1930. i = 0
  1931. while i < len(trs):
  1932. tr = trs[i]
  1933. if len(tr.find_all('td'))==2 and tr.td!=None and tr.td.findNextSibling()!=None:
  1934. td1_text =tr.td.text
  1935. td2_text =tr.td.findNextSibling().text
  1936. if re.search('业绩', td1_text)!=None and len(td1_text)<10 and len(re.findall('(\d、|(\d))?[-\w()、]+(工程|项目|勘察|设计|施工|监理|总承包|采购|更新)', td2_text))>=2:
  1937. # del_tag = tr.extract()
  1938. # print('删除表格业绩内容', del_tag.text)
  1939. del_trs.append(tr)
  1940. elif tr.td != None and re.search('^业绩|业绩$', tr.td.text.strip()) and len(tr.td.text.strip())<25:
  1941. rows = tr.td.attrs.get('rowspan', '')
  1942. cols = tr.td.attrs.get('colspan', '')
  1943. if rows.isdigit() and int(rows)>2:
  1944. for j in range(int(rows)):
  1945. if i+j < len(trs):
  1946. del_trs.append(trs[i+j])
  1947. i += j
  1948. elif cols.isdigit() and int(cols)>3 and len(tr.find_all('td'))==1 and i+2 < len(trs):
  1949. next_tr_cols = 0
  1950. td_num = 0
  1951. for td in trs[i+1].find_all('td'):
  1952. td_num += 1
  1953. if td.attrs.get('colspan', '').isdigit():
  1954. next_tr_cols += int(td.attrs.get('colspan', ''))
  1955. if next_tr_cols == int(cols):
  1956. del_trs.append(tr)
  1957. for j in range(1,len(trs)-i):
  1958. if len(trs[i+j].find_all('td')) == 1:
  1959. break
  1960. elif len(trs[i+j].find_all('td')) >= td_num-1:
  1961. del_trs.append(trs[i+j])
  1962. else:
  1963. break
  1964. i += j
  1965. i += 1
  1966. for tr in del_trs:
  1967. del_tag = tr.extract()
  1968. # print('删除表格业绩内容', del_tag.text)
  1969. def split_header(soup):
  1970. '''
  1971. 处理 空格分割多个表头的情况 : 主要标的名称 规格型号(或服务要求) 主要标的数量 主要标的单价 合同金额(万元)
  1972. :param soup: bs4 soup 对象
  1973. :return:
  1974. '''
  1975. header = []
  1976. attrs = []
  1977. flag = 0
  1978. tag = None
  1979. for p in soup.find_all('p'):
  1980. text = p.get_text()
  1981. if re.search('主要标的数量\s+主要标的单价((万?元))?\s+合同金额', text):
  1982. header = re.split('\s{3,}', text) if re.search('\s{3,}', text) else re.split('\s+', text)
  1983. flag = 1
  1984. tag = p
  1985. continue
  1986. if flag:
  1987. attrs = re.split('\s{3,}', text) if re.search('\s{3,}', text) else re.split('\s+', text)
  1988. if header and len(header) == len(attrs) and tag:
  1989. s = ""
  1990. for head, attr in zip(header, attrs):
  1991. s += head + ':' + attr + ','
  1992. tag.string = s
  1993. p.extract()
  1994. break
  1995. def get_preprocessed_article(articles,cost_time = dict(),useselffool=True):
  1996. '''
  1997. :param articles: 待处理的article source html
  1998. :param useselffool: 是否使用selffool
  1999. :return: list_articles
  2000. '''
  2001. list_articles = []
  2002. for article in articles:
  2003. doc_id = article[0]
  2004. sourceContent = article[1]
  2005. sourceContent = re.sub("<html>|</html>|<body>|</body>","",sourceContent)
  2006. sourceContent = re.sub("##attachment##","",sourceContent)
  2007. sourceContent = sourceContent.replace('<br/>', '<br>')
  2008. sourceContent = re.sub("<br>(\s{0,}<br>)+","<br>",sourceContent)
  2009. # for br_match in re.findall("[^>]+?<br>",sourceContent):
  2010. # _new = re.sub("<br>","",br_match)
  2011. # # <br>标签替换为<p>标签
  2012. # if not re.search("^\s+$",_new):
  2013. # _new = '<p>'+_new + '</p>'
  2014. # # print(br_match,_new)
  2015. # sourceContent = sourceContent.replace(br_match,_new,1)
  2016. _send_doc_id = article[3]
  2017. _title = article[4]
  2018. page_time = article[5]
  2019. web_source_no = article[6]
  2020. '''特别数据源对 html 做特别修改'''
  2021. if web_source_no in ['DX000202-1']:
  2022. sourceContent = special_treatment(sourceContent, web_source_no)
  2023. #表格处理
  2024. key_preprocess = "tableToText"
  2025. start_time = time.time()
  2026. # article_processed = tableToText(BeautifulSoup(sourceContent,"lxml"))
  2027. article_processed = BeautifulSoup(sourceContent,"lxml")
  2028. if re.search('主要标的数量(&nbsp;|\s)+主要标的单价((万?元))?(&nbsp;|\s)+合同金额', sourceContent): #处理 空格分割多个表头的情况
  2029. split_header(article_processed)
  2030. '''表格业绩内容删除'''
  2031. del_tabel_achievement(article_processed)
  2032. '''特别数据源对 BeautifulSoup(html) 做特别修改'''
  2033. if web_source_no in ["00753-14","DX008357-11","18021-2"]:
  2034. article_processed = special_treatment(article_processed, web_source_no)
  2035. for _soup in article_processed.descendants:
  2036. # 识别无标签文本,添加<span>标签
  2037. if not _soup.name and not _soup.parent.string and _soup.string.strip()!="":
  2038. # print(_soup.parent.string,_soup.string.strip())
  2039. _soup.wrap(article_processed.new_tag("span"))
  2040. # print(article_processed)
  2041. # 正文和附件内容限制字数30000
  2042. article_processed = article_limit(article_processed, limit_words=30000)
  2043. # 把每个附件识别对应的html放回原来出现的位置
  2044. article_processed = attachment_filelink(article_processed)
  2045. article_processed = get_preprocessed_outline(article_processed)
  2046. # print('article_processed')
  2047. article_processed = tableToText(article_processed)
  2048. article_processed = segment(article_processed)
  2049. article_processed = article_processed.replace('(', '(').replace(')', ')') #2022/8/10 统一为中文括号
  2050. article_processed = article_processed.replace(':', ':') #2023/1/5 统一为中文冒号
  2051. article_processed = article_processed.replace('.','.').replace('-', '-') # 2021/12/01 修正OCR识别PDF小数点错误问题
  2052. article_processed = article_processed.replace('报价限价', '招标限价') #2021/12/17 由于报价限价预测为中投标金额所以修改
  2053. article_processed = article_processed.replace('成交工程价款', '成交工程价') # 2021/12/21 修正为中标价
  2054. article_processed = re.sub('任务(?=编号[::])', '项目',article_processed) # 2022/08/10 修正为项目编号
  2055. article_processed = article_processed.replace('招标(建设)单位', '招标单位') #2022/8/10 修正预测不到表达
  2056. article_processed = re.sub("采购商(?=[^\u4e00-\u9fa5]|名称)", "招标人", article_processed)
  2057. article_processed = re.sub('(招标|采购)人(概况|信息):?[,。]', '采购人信息:', article_processed) # 2022/8/10统一表达
  2058. article_processed = article_processed.replace('\(%)', '') # 中标(成交)金额(元)\(%):498888.00, 处理 江西省政府采购网 金额特殊问题
  2059. article_processed = re.sub('金额:?((可填写下浮率?、折扣率?或费率|拟签含税总单价总计|[^万元()\d]{8,20})):?', '金额:', article_processed) # 中标(成交)金额:(可填写下浮率、折扣率或费率):29.3万元 金额特殊问题
  2060. '''去除业绩内容'''
  2061. article_processed = del_achievement(article_processed)
  2062. # 修复OCR金额中“,”、“。”识别错误
  2063. article_processed_list = article_processed.split("##attachment##")
  2064. if len(article_processed_list)>1:
  2065. attachment_text = article_processed_list[1]
  2066. for _match in re.finditer("\d。\d{2}",attachment_text):
  2067. _match_text = _match.group()
  2068. attachment_text = attachment_text.replace(_match_text,_match_text.replace("。","."),1)
  2069. # for _match in re.finditer("(\d,\d{3})[,,.]",attachment_text):
  2070. for _match in re.finditer("\d,(?=\d{3}[^\d])",attachment_text):
  2071. _match_text = _match.group()
  2072. attachment_text = attachment_text.replace(_match_text,_match_text.replace(",",","),1)
  2073. article_processed_list[1] = attachment_text
  2074. article_processed = "##attachment##".join(article_processed_list)
  2075. '''特别数据源对 预处理后文本 做特别修改'''
  2076. 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']:
  2077. article_processed = special_treatment(article_processed, web_source_no)
  2078. # 提取bidway
  2079. list_bidway = extract_bidway(article_processed, _title)
  2080. if list_bidway:
  2081. bidway = list_bidway[0].get("body")
  2082. # bidway名称统一规范
  2083. bidway = bidway_integrate(bidway)
  2084. else:
  2085. bidway = ""
  2086. # 修正被","逗号分隔的时间
  2087. repair_time = re.compile("[12]\d,?\d,?\d,?[-—-―/年],?[0-1]?\d,?[-—-―/月],?[0-3]?\d,?[日号]?,?(?:上午|下午)?,?[0-2]?\d,?:,?[0-6]\d,?:,?[0-6]\d|"
  2088. "[12]\d,?\d,?\d,?[-—-―/年],?[0-1]?\d,?[-—-―/月],?[0-3]?\d,?[日号]?,?(?:上午|下午)?,?[0-2]?\d,?[:时点],?[0-6]\d分?|"
  2089. "[12]\d,?\d,?\d,?[-—-―/年],?[0-1]?\d,?[-—-―/月],?[0-3]?\d,?[日号]?,?(?:上午|下午)?,?[0-2]?\d,?[时点]|"
  2090. "[12]\d,?\d,?\d,?[-—-―/年],?[0-1]?\d,?[-—-―/月],?[0-3]?\d,?[日号]|"
  2091. "[0-2]?\d,?:,?[0-6]\d,?:,?[0-6]\d"
  2092. )
  2093. for _time in set(re.findall(repair_time,article_processed)):
  2094. if re.search(",",_time):
  2095. _time2 = re.sub(",", "", _time)
  2096. item = re.search("[12]\d{3}[-—-―/][0-1]?\d[-—-―/][0-3]\d(?=\d)", _time2)
  2097. if item:
  2098. _time2 = _time2.replace(item.group(),item.group() + " ")
  2099. article_processed = article_processed.replace(_time, _time2)
  2100. else:
  2101. item = re.search("[12]\d{3}[-—-―/][0-1]?\d[-—-―/][0-3]\d(?=\d)", _time)
  2102. if item:
  2103. _time2 = _time.replace(item.group(),item.group() + " ")
  2104. article_processed = article_processed.replace(_time, _time2)
  2105. # print('re_rtime',re.findall(repair_time,article_processed))
  2106. # log(article_processed)
  2107. if key_preprocess not in cost_time:
  2108. cost_time[key_preprocess] = 0
  2109. cost_time[key_preprocess] += round(time.time()-start_time,2)
  2110. #article_processed = article[1]
  2111. _article = Article(doc_id,article_processed,sourceContent,_send_doc_id,_title,
  2112. bidway=bidway)
  2113. _article.fingerprint = getFingerprint(_title+sourceContent)
  2114. _article.page_time = page_time
  2115. list_articles.append(_article)
  2116. return list_articles
  2117. def get_preprocessed_sentences(list_articles,useselffool=True,cost_time=dict()):
  2118. '''
  2119. :param list_articles: 经过预处理的article text
  2120. :return: list_sentences
  2121. '''
  2122. list_sentences = []
  2123. list_outlines = []
  2124. for article in list_articles:
  2125. list_sentences_temp = []
  2126. list_entitys_temp = []
  2127. doc_id = article.id
  2128. _send_doc_id = article.doc_id
  2129. _title = article.title
  2130. #表格处理
  2131. key_preprocess = "tableToText"
  2132. start_time = time.time()
  2133. article_processed = article.content
  2134. if len(_title)<100 and _title not in article_processed: # 把标题放到正文
  2135. article_processed = _title + ',' + article_processed # 2023/01/06 标题正文加逗号分割,预防标题后面是产品,正文开头是公司实体,实体识别把产品和公司作为整个角色实体
  2136. attachment_begin_index = -1
  2137. if key_preprocess not in cost_time:
  2138. cost_time[key_preprocess] = 0
  2139. cost_time[key_preprocess] += time.time()-start_time
  2140. #nlp处理
  2141. if article_processed is not None and len(article_processed)!=0:
  2142. split_patten = "。"
  2143. sentences = []
  2144. _begin = 0
  2145. sentences_set = set()
  2146. for _iter in re.finditer(split_patten,article_processed):
  2147. _sen = article_processed[_begin:_iter.span()[1]]
  2148. if len(_sen)>0 and _sen not in sentences_set:
  2149. # 标识在附件里的句子
  2150. if re.search("##attachment##",_sen):
  2151. attachment_begin_index = len(sentences)
  2152. # _sen = re.sub("##attachment##","",_sen)
  2153. sentences.append(_sen)
  2154. sentences_set.add(_sen)
  2155. _begin = _iter.span()[1]
  2156. _sen = article_processed[_begin:]
  2157. if re.search("##attachment##", _sen):
  2158. # _sen = re.sub("##attachment##", "", _sen)
  2159. attachment_begin_index = len(sentences)
  2160. if len(_sen)>0 and _sen not in sentences_set:
  2161. sentences.append(_sen)
  2162. sentences_set.add(_sen)
  2163. # 解析outline大纲分段
  2164. outline_list = []
  2165. if re.search("##split##",article.content):
  2166. temp_sentences = []
  2167. last_sentence_index = (-1,-1)
  2168. outline_index = 0
  2169. for sentence_index in range(len(sentences)):
  2170. sentence_text = sentences[sentence_index]
  2171. for _ in re.findall("##split##", sentence_text):
  2172. _match = re.search("##split##", sentence_text)
  2173. if last_sentence_index[0] > -1:
  2174. sentence_begin_index,wordOffset_begin = last_sentence_index
  2175. sentence_end_index = sentence_index
  2176. wordOffset_end = _match.start()
  2177. if sentence_begin_index<attachment_begin_index and sentence_end_index>=attachment_begin_index:
  2178. outline_list.append(Outline(doc_id,outline_index,'',sentence_begin_index,attachment_begin_index-1,wordOffset_begin,len(sentences[attachment_begin_index-1])))
  2179. else:
  2180. outline_list.append(Outline(doc_id,outline_index,'',sentence_begin_index,sentence_end_index,wordOffset_begin,wordOffset_end))
  2181. outline_index += 1
  2182. sentence_text = re.sub("##split##", "", sentence_text,count=1)
  2183. last_sentence_index = (sentence_index,_match.start())
  2184. temp_sentences.append(sentence_text)
  2185. if attachment_begin_index>-1 and last_sentence_index[0]<attachment_begin_index:
  2186. 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])))
  2187. else:
  2188. outline_list.append(Outline(doc_id,outline_index,'',last_sentence_index[0],len(sentences)-1,last_sentence_index[1],len(temp_sentences[-1])))
  2189. sentences = temp_sentences
  2190. #解析outline的outline_text内容
  2191. for _outline in outline_list:
  2192. if _outline.sentence_begin_index==_outline.sentence_end_index:
  2193. _text = sentences[_outline.sentence_begin_index][_outline.wordOffset_begin:_outline.wordOffset_end]
  2194. else:
  2195. _text = ""
  2196. for idx in range(_outline.sentence_begin_index,_outline.sentence_end_index+1):
  2197. if idx==_outline.sentence_begin_index:
  2198. _text += sentences[idx][_outline.wordOffset_begin:]
  2199. elif idx==_outline.sentence_end_index:
  2200. _text += sentences[idx][:_outline.wordOffset_end]
  2201. else:
  2202. _text += sentences[idx]
  2203. _outline.outline_text = _text
  2204. _outline_summary = re.split("[::,]",_text,1)[0]
  2205. if len(_outline_summary)<30:
  2206. _outline.outline_summary = _outline_summary
  2207. # print(_outline.outline_index,_outline.outline_text)
  2208. article.content = "".join(sentences)
  2209. # sentences.append(article_processed[_begin:])
  2210. lemmas = []
  2211. doc_offsets = []
  2212. dep_types = []
  2213. dep_tokens = []
  2214. time1 = time.time()
  2215. '''
  2216. tokens_all = fool.cut(sentences)
  2217. #pos_all = fool.LEXICAL_ANALYSER.pos(tokens_all)
  2218. #ner_tag_all = fool.LEXICAL_ANALYSER.ner_labels(sentences,tokens_all)
  2219. ner_entitys_all = fool.ner(sentences)
  2220. '''
  2221. #限流执行
  2222. key_nerToken = "nerToken"
  2223. start_time = time.time()
  2224. # tokens_all = getTokens(sentences,useselffool=useselffool)
  2225. tokens_all = getTokens([re.sub("##attachment_begin##|##attachment_end##","",_sen) for _sen in sentences],useselffool=useselffool)
  2226. if key_nerToken not in cost_time:
  2227. cost_time[key_nerToken] = 0
  2228. cost_time[key_nerToken] += round(time.time()-start_time,2)
  2229. in_attachment = False
  2230. for sentence_index in range(len(sentences)):
  2231. sentence_text = sentences[sentence_index]
  2232. if re.search("##attachment_begin##",sentence_text):
  2233. in_attachment = True
  2234. sentence_text = re.sub("##attachment_begin##","",sentence_text)
  2235. if re.search("##attachment_end##",sentence_text):
  2236. in_attachment = False
  2237. sentence_text = re.sub("##attachment_end##", "", sentence_text)
  2238. if sentence_index >= attachment_begin_index and attachment_begin_index!=-1:
  2239. in_attachment = True
  2240. tokens = tokens_all[sentence_index]
  2241. #pos_tag = pos_all[sentence_index]
  2242. pos_tag = ""
  2243. ner_entitys = ""
  2244. 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))
  2245. if len(list_sentences_temp)==0:
  2246. list_sentences_temp.append(Sentences(doc_id=doc_id,sentence_index=0,sentence_text="sentence_text",tokens=[],pos_tags=[],ner_tags=""))
  2247. list_sentences.append(list_sentences_temp)
  2248. list_outlines.append(outline_list)
  2249. article.content = re.sub("##attachment_begin##|##attachment_end##", "", article.content)
  2250. return list_sentences,list_outlines
  2251. def get_preprocessed_entitys(list_sentences,useselffool=True,cost_time=dict()):
  2252. '''
  2253. :param list_sentences:分局情况
  2254. :param cost_time:
  2255. :return: list_entitys
  2256. '''
  2257. list_entitys = []
  2258. for list_sentence in list_sentences:
  2259. sentences = []
  2260. list_entitys_temp = []
  2261. for _sentence in list_sentence:
  2262. sentences.append(_sentence.sentence_text)
  2263. lemmas = []
  2264. doc_offsets = []
  2265. dep_types = []
  2266. dep_tokens = []
  2267. time1 = time.time()
  2268. '''
  2269. tokens_all = fool.cut(sentences)
  2270. #pos_all = fool.LEXICAL_ANALYSER.pos(tokens_all)
  2271. #ner_tag_all = fool.LEXICAL_ANALYSER.ner_labels(sentences,tokens_all)
  2272. ner_entitys_all = fool.ner(sentences)
  2273. '''
  2274. #限流执行
  2275. key_nerToken = "nerToken"
  2276. start_time = time.time()
  2277. found_yeji = 0 # 2021/8/6 增加判断是否正文包含评标结果 及类似业绩判断用于过滤后面的金额
  2278. # found_pingbiao = False
  2279. ner_entitys_all = getNers(sentences,useselffool=useselffool)
  2280. if key_nerToken not in cost_time:
  2281. cost_time[key_nerToken] = 0
  2282. cost_time[key_nerToken] += round(time.time()-start_time,2)
  2283. company_dict = set()
  2284. company_index = dict((i,set()) for i in range(len(list_sentence)))
  2285. for sentence_index in range(len(list_sentence)):
  2286. list_sentence_entitys = []
  2287. sentence_text = list_sentence[sentence_index].sentence_text
  2288. tokens = list_sentence[sentence_index].tokens
  2289. doc_id = list_sentence[sentence_index].doc_id
  2290. in_attachment = list_sentence[sentence_index].in_attachment
  2291. list_tokenbegin = []
  2292. begin = 0
  2293. for i in range(0,len(tokens)):
  2294. list_tokenbegin.append(begin)
  2295. begin += len(str(tokens[i]))
  2296. list_tokenbegin.append(begin+1)
  2297. #pos_tag = pos_all[sentence_index]
  2298. pos_tag = ""
  2299. ner_entitys = ner_entitys_all[sentence_index]
  2300. '''正则识别角色实体 经营部|经销部|电脑部|服务部|复印部|印刷部|彩印部|装饰部|修理部|汽修部|修理店|零售店|设计店|服务店|家具店|专卖店|分店|文具行|商行|印刷厂|修理厂|维修中心|修配中心|养护中心|服务中心|会馆|文化馆|超市|门市|商场|家具城|印刷社|经销处'''
  2301. for it in re.finditer(
  2302. '(?P<text_key_word>(((单一来源|中标|中选|中价|成交)(供应商|供货商|服务商|候选人|单位|人))|(供应商|供货商|服务商|候选人))(名称)?[为::]+)(?P<text>([()\w]{5,20})(厂|中心|超市|门市|商场|工作室|文印室|城|部|店|站|馆|行|社|处))[,。]',
  2303. sentence_text):
  2304. for k, v in it.groupdict().items():
  2305. if k == 'text_key_word':
  2306. keyword = v
  2307. if k == 'text':
  2308. entity = v
  2309. b = it.start() + len(keyword)
  2310. e = it.end() - 1
  2311. if (b, e, 'location', entity) in ner_entitys:
  2312. ner_entitys.remove((b, e, 'location', entity))
  2313. ner_entitys.append((b, e, 'company', entity))
  2314. elif (b, e, 'org', entity) not in ner_entitys and (b, e, 'company', entity) not in ner_entitys:
  2315. ner_entitys.append((b, e, 'company', entity))
  2316. for it in re.finditer(
  2317. '(?P<text_key_word>((建设|招租|招标|采购)(单位|人)|业主)(名称)?[为::]+)(?P<text>\w{2,4}[省市县区镇]([()\w]{2,20})(管理处|办公室|委员会|村委会|纪念馆|监狱|管教所|修养所|社区|农场|林场|羊场|猪场|石场|村|幼儿园))[,。]',
  2318. sentence_text):
  2319. for k, v in it.groupdict().items():
  2320. if k == 'text_key_word':
  2321. keyword = v
  2322. if k == 'text':
  2323. entity = v
  2324. b = it.start() + len(keyword)
  2325. e = it.end() - 1
  2326. if (b, e, 'location', entity) in ner_entitys:
  2327. ner_entitys.remove((b, e, 'location', entity))
  2328. ner_entitys.append((b, e, 'org', entity))
  2329. if (b, e, 'org', entity) not in ner_entitys and (b, e, 'company', entity) not in ner_entitys:
  2330. ner_entitys.append((b, e, 'org', entity))
  2331. for ner_entity in ner_entitys:
  2332. if ner_entity[2] in ['company','org']:
  2333. company_dict.add((ner_entity[2],ner_entity[3]))
  2334. company_index[sentence_index].add((ner_entity[0],ner_entity[1]))
  2335. #识别package
  2336. #识别实体
  2337. for ner_entity in ner_entitys:
  2338. begin_index_temp = ner_entity[0]
  2339. end_index_temp = ner_entity[1]
  2340. entity_type = ner_entity[2]
  2341. entity_text = ner_entity[3]
  2342. if entity_type in ["org","company"] and not isLegalEnterprise(entity_text):
  2343. continue
  2344. # 实体长度限制
  2345. if entity_type in ["org","company"] and len(entity_text)>30:
  2346. continue
  2347. if entity_type == "person" and len(entity_text) > 20:
  2348. continue
  2349. elif entity_type=="person" and len(entity_text)>10 and len(re.findall("[\u4e00-\u9fa5]",entity_text))<len(entity_text)/2:
  2350. continue
  2351. for j in range(len(list_tokenbegin)):
  2352. if list_tokenbegin[j]==begin_index_temp:
  2353. begin_index = j
  2354. break
  2355. elif list_tokenbegin[j]>begin_index_temp:
  2356. begin_index = j-1
  2357. break
  2358. begin_index_temp += len(str(entity_text))
  2359. for j in range(begin_index,len(list_tokenbegin)):
  2360. if list_tokenbegin[j]>=begin_index_temp:
  2361. end_index = j-1
  2362. break
  2363. entity_id = "%s_%d_%d_%d"%(doc_id,sentence_index,begin_index,end_index)
  2364. #去掉标点符号
  2365. entity_text = re.sub("[,,。:!&@$\*]","",entity_text)
  2366. entity_text = entity_text.replace("(","(").replace(")",")") if isinstance(entity_text,str) else entity_text
  2367. # 组织机构实体名称补充
  2368. if entity_type in ["org", "company"]:
  2369. fix_name = re.search("(有限)([责贵]?任?)(公?司?)",entity_text)
  2370. if fix_name:
  2371. if len(fix_name.group(2))>0:
  2372. entity_text = entity_text.replace(fix_name.group(), "有限责任公司")
  2373. elif len(fix_name.group(3))>0:
  2374. entity_text = entity_text.replace(fix_name.group(), "有限公司")
  2375. elif re.search("有限$", entity_text):
  2376. entity_text = re.sub("有限$","有限公司",entity_text)
  2377. 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))
  2378. # 标记文章末尾的"发布人”、“发布时间”实体
  2379. if sentence_index==len(list_sentence)-1:
  2380. if len(list_sentence_entitys[-2:])>2:
  2381. second2last = list_sentence_entitys[-2]
  2382. last = list_sentence_entitys[-1]
  2383. if (second2last.entity_type in ["company",'org'] and last.entity_type=="time") or (
  2384. second2last.entity_type=="time" and last.entity_type in ["company",'org']):
  2385. if last.wordOffset_begin - second2last.wordOffset_end < 6 and len(sentence_text) - last.wordOffset_end<6:
  2386. last.is_tail = True
  2387. second2last.is_tail = True
  2388. #使用正则识别金额
  2389. entity_type = "money"
  2390. #money_patten_str = "(([1-9][\d,,]*(?:\.\d+)?[百千万亿]?[\(\)()元整]+)|([零壹贰叁肆伍陆柒捌玖拾佰仟萬億十百千万亿元角分]{3,})|(?:[¥¥]+,?|报价|标价)[(\(]?([万])?元?[)\)]?[::]?.{,7}?([1-9][\d,,]*(?:\.\d+)?(?:,?)[百千万亿]?)|([1-9][\d,,]*(?:\.\d+)?(?:,?)[百千万亿]?)[\((]?([万元]{1,2}))*"
  2391. # list_money_pattern = {"cn":"(()()(?P<money_cn>[零壹贰叁肆伍陆柒捌玖拾佰仟萬億圆十百千万亿元角分]{3,})())",
  2392. # "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*[)\)]?))",
  2393. # "front_m":"((?P<text_front_m>(?:[(\(]?\s*(?P<unit_front_m_before>[万元]+)\s*[)\)])\s*[,,::]*(\s*[^壹贰叁肆伍陆柒捌玖拾佰仟萬億分万元]{,7}?))(?P<money_front_m>[0-9][\d,]*(?:\.\d+)?(?:,?)[百千万亿元]*)())",
  2394. # "behind_m":"(()()(?P<money_behind_m>[0-9][\d,,]*(?:\.\d+)?(?:,?)[百千万亿]*)[\((]?(?P<unit_behind_m>[万元]+(?P<filter_unit3>[台个只]*))[\))]?)"}
  2395. list_money_pattern = {"cn":"(()()(?P<money_cn>[零壹贰叁肆伍陆柒捌玖拾佰仟萬億圆十百千万亿元角分]{3,})())",
  2396. "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+)?(?P<science_key_word>(E-?\d+))?(?:,?)[百千]{,1})(?:[(\(]?(?P<filter_>[%])*\s*(单位[::])?(?P<unit_key_word_behind>[万亿]?(?:[美日欧]元|元)?(?P<filter_unit1>[台只吨斤棵株页亩方条天]*))\s*[)\)]?))",
  2397. "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+)?(?P<science_front_m>(E-?\d+))?(?:,?)[百千]*)())",
  2398. "behind_m":"(()()(?P<money_behind_m>-*[0-9][\d,]*(?:\.\d+)?(?P<science_behind_m>(E-?\d+))?(?:,?)[百千]*)(人民币)?[\((]?(?P<unit_behind_m>[万亿]?(?:[美日欧]元|元)(?P<filter_unit3>[台个只吨斤棵株页亩方条米]*))[\))]?)"}
  2399. # 2021/7/19 调整金额,单位提取正则,修复部分金额因为单位提取失败被过滤问题。
  2400. 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"]))
  2401. set_begin = set()
  2402. # for pattern_key in list_money_pattern.keys():
  2403. # for pattern_key in ["cn","key_word","behind_m","front_m"]:
  2404. # # pattern = re.compile(list_money_pattern[pattern_key])
  2405. # 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+)?(?:,?)[百千万亿元]*)())*")
  2406. # all_match = re.findall(pattern, sentence_text)
  2407. # index = 0
  2408. # for i in range(len(all_match)):
  2409. # if len(all_match[i][0])>0:
  2410. # print("===",all_match[i])
  2411. # #print(all_match[i][0])
  2412. # unit = ""
  2413. # entity_text = all_match[i][3]
  2414. # if pattern_key in ["key_word","front_m"]:
  2415. # unit = all_match[i][1]
  2416. # if pattern_key=="key_word":
  2417. # if all_match[i][1]=="" and all_match[i][4]!="":
  2418. # unit = all_match[i][4]
  2419. # else:
  2420. # unit = all_match[i][4]
  2421. # if entity_text.find("元")>=0:
  2422. # unit = ""
  2423. #
  2424. # index += len(all_match[i][0])-len(entity_text)-len(all_match[i][4])#-len(all_match[i][1])-len(all_match[i][2])#整个提出来的作为实体->数字部分作为整体,否则会丢失特征
  2425. # begin_index_temp = index
  2426. # for j in range(len(list_tokenbegin)):
  2427. # if list_tokenbegin[j]==index:
  2428. # begin_index = j
  2429. # break
  2430. # elif list_tokenbegin[j]>index:
  2431. # begin_index = j-1
  2432. # break
  2433. # index += len(str(entity_text))+len(all_match[i][4])#+len(all_match[i][2])+len(all_match[i][1])#整个提出来的作为实体
  2434. # end_index_temp = index
  2435. # #index += len(str(all_match[i][0]))
  2436. # for j in range(begin_index,len(list_tokenbegin)):
  2437. # if list_tokenbegin[j]>=index:
  2438. # end_index = j-1
  2439. # break
  2440. # entity_id = "%s_%d_%d_%d"%(doc_id,sentence_index,begin_index,end_index)
  2441. #
  2442. # entity_text = re.sub("[^0-9.零壹贰叁肆伍陆柒捌玖拾佰仟萬億十百千万亿元角分]","",entity_text)
  2443. # if len(unit)>0:
  2444. # entity_text = str(getUnifyMoney(entity_text)*getMultipleFactor(unit[0]))
  2445. # else:
  2446. # entity_text = str(getUnifyMoney(entity_text))
  2447. #
  2448. # _exists = False
  2449. # for item in list_sentence_entitys:
  2450. # if item.entity_id==entity_id and item.entity_type==entity_type:
  2451. # _exists = True
  2452. # if not _exists:
  2453. # if float(entity_text)>1:
  2454. # 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))
  2455. #
  2456. # else:
  2457. # index += 1
  2458. # if re.search('评标结果|候选人公示', sentence_text):
  2459. # found_pingbiao = True
  2460. if re.search('业绩', sentence_text):
  2461. found_yeji += 1
  2462. if found_yeji >= 2: # 过滤掉业绩后面的所有金额
  2463. all_match = []
  2464. else:
  2465. all_match = re.finditer(pattern_money, sentence_text)
  2466. index = 0
  2467. for _match in all_match:
  2468. if len(_match.group())>0:
  2469. # print("===",_match.group())
  2470. # # print(_match.groupdict())
  2471. notes = '' # 2021/7/20 新增备注金额大写或金额单位 if 金额大写 notes=大写 elif 单位 notes=单位
  2472. unit = ""
  2473. entity_text = ""
  2474. text_beforeMoney = ""
  2475. filter = ""
  2476. filter_unit = False
  2477. notSure = False
  2478. science = ""
  2479. if re.search('业绩', sentence_text[:_match.span()[0]]): # 2021/7/21过滤掉业绩后面金额
  2480. # print('金额在业绩后面: ', _match.group(0))
  2481. found_yeji += 1
  2482. break
  2483. if (re.search('电话|编码|编号|号码|日期|时间|账号', sentence_text[max(0, _match.start()-12): _match.end()]) or re.search('^[a-zA-Z0-9+-]', sentence_text[_match.end():])) and re.search('[元¥¥]', _match.group(0)) == None:
  2484. continue
  2485. for k,v in _match.groupdict().items():
  2486. if v!="" and v is not None:
  2487. if k=='text_key_word':
  2488. notSure = True
  2489. if k.split("_")[0]=="money":
  2490. entity_text = v
  2491. if entity_text.endswith(',00'): # 金额逗号后面不可能为两个0结尾,应该小数点识别错,直接去掉
  2492. entity_text = entity_text[:-3]
  2493. if k.split("_")[0]=="unit":
  2494. if v=='万元' or unit=="": # 处理 预算金额(元):160万元 这种出现前后单位不一致情况
  2495. unit = v
  2496. if k.split("_")[0]=="text":
  2497. text_beforeMoney = v
  2498. if k.split("_")[0]=="filter":
  2499. filter = v
  2500. if re.search("filter_unit",k) is not None:
  2501. filter_unit = True
  2502. if k.split("_")[0] == 'science':
  2503. science = v
  2504. # print(_match.group())
  2505. # print(entity_text,unit,text_beforeMoney,filter,filter_unit)
  2506. if re.search('(^\d{2,},\d{4,}万?$)|(^\d{2,},\d{2}万?$)', entity_text.strip()): # 2021/7/19 修正OCR识别小数点为逗号
  2507. if re.search('[幢栋号楼层]', sentence_text[max(0, _match.span()[0]-2):_match.span()[0]]):
  2508. entity_text = re.sub('\d+,', '', entity_text)
  2509. else:
  2510. entity_text = entity_text.replace(',', '.')
  2511. # print(' 修正OCR识别小数点为逗号')
  2512. if entity_text.find("元")>=0:
  2513. unit = ""
  2514. if unit == "": #2021/7/21 有明显金额特征的补充单位,避免被过滤
  2515. if ('¥' in text_beforeMoney or '¥' in text_beforeMoney):
  2516. unit = '元'
  2517. # print('明显金额特征补充单位 元')
  2518. elif re.search('[单报标限]价|金额|价格|(监理|设计|勘察)(服务)?费[::为]+$', text_beforeMoney.strip()) and \
  2519. re.search('\d{5,}',entity_text) and re.search('^0|1[3|4|5|6|7|8|9]\d{9}',entity_text)==None:
  2520. unit = '元'
  2521. # print('明显金额特征补充单位 元')
  2522. elif re.search('(^\d{,3}(,?\d{3})+(\.\d{2,7},?)$)|(^\d{,3}(,\d{3})+,?$)',entity_text):
  2523. unit = '元'
  2524. # print('明显金额特征补充单位 元')
  2525. if unit.find("万") >= 0 and entity_text.find("万") >= 0: #2021/7/19修改为金额文本有万,不计算单位
  2526. # print('修正金额及单位都有万, 金额:',entity_text, '单位:',unit)
  2527. unit = "元"
  2528. if re.search('.*万元万元', entity_text): #2021/7/19 修正两个万元
  2529. # print(' 修正两个万元',entity_text)
  2530. entity_text = entity_text.replace('万元万元','万元')
  2531. else:
  2532. if filter_unit:
  2533. continue
  2534. if filter!="":
  2535. continue
  2536. index = _match.span()[0]+len(text_beforeMoney)
  2537. begin_index_temp = index
  2538. for j in range(len(list_tokenbegin)):
  2539. if list_tokenbegin[j]==index:
  2540. begin_index = j
  2541. break
  2542. elif list_tokenbegin[j]>index:
  2543. begin_index = j-1
  2544. break
  2545. index = _match.span()[1]
  2546. end_index_temp = index
  2547. #index += len(str(all_match[i][0]))
  2548. for j in range(begin_index,len(list_tokenbegin)):
  2549. if list_tokenbegin[j]>=index:
  2550. end_index = j-1
  2551. break
  2552. entity_id = "%s_%d_%d_%d"%(doc_id,sentence_index,begin_index,end_index)
  2553. symbol = '-' if entity_text.startswith('-') and not entity_text.startswith('--') and re.search('\d+$', sentence_text[:begin_index_temp]) == None else '' # 负值金额前面保留负号 ,后面这些不作为负金额 起拍价:105.29-200.46万元 预 算 --- 350000.0
  2554. entity_text = re.sub("[^0-9.零壹贰叁肆伍陆柒捌玖拾佰仟萬億圆十百千万亿元角分]","",entity_text)
  2555. # print('转换前金额:', entity_text, '单位:', unit, '备注:',notes, 'text_beforeMoney:',text_beforeMoney)
  2556. if re.search('总投资|投资总额|总预算|总概算|投资规模|批复概算', sentence_text[max(0, _match.span()[0] - 8):_match.span()[1]]): # 2021/8/5过滤掉总投资金额
  2557. # print('总投资金额: ', _match.group(0))
  2558. notes = '总投资'
  2559. elif re.search('投资|概算', sentence_text[max(0, _match.span()[0] - 8):_match.span()[1]]): # 2021/11/18 投资金额不作为招标金额
  2560. notes = '投资'
  2561. elif re.search('工程造价', sentence_text[max(0, _match.span()[0] - 8):_match.span()[1]]): # 2021/12/20 工程造价不作为招标金额
  2562. notes = '工程造价'
  2563. elif (re.search('保证金', sentence_text[max(0, _match.span()[0] - 5):_match.span()[1]])
  2564. or re.search('保证金的?(缴纳)?(金额|金\?|额|\?)?[\((]*(万?元|为?人民币|大写|调整|变更|已?修改|更改|更正)?[\))]*[::为]',
  2565. sentence_text[max(0, _match.span()[0] - 10):_match.span()[1]])
  2566. or re.search('保证金由[\d.,]+.{,3}(变更|修改|更改|更正|调整?)为',
  2567. sentence_text[max(0, _match.span()[0] - 15):_match.span()[1]])):
  2568. notes = '保证金'
  2569. # print('保证金信息:', sentence_text[max(0, _match.span()[0] - 15):_match.span()[1]])
  2570. elif re.search('成本(警戒|预警)(线|价|值)[^0-9元]{,10}',
  2571. sentence_text[max(0, _match.span()[0] - 10):_match.span()[0]]):
  2572. notes = '成本警戒线'
  2573. elif re.search('(监理|设计|勘察)(服务)?费(报价)?[约为:]', sentence_text[_match.span()[0]:_match.span()[1]]):
  2574. cost_re = re.search('(监理|设计|勘察)(服务)?费', sentence_text[_match.span()[0]:_match.span()[1]])
  2575. notes = cost_re.group(1)
  2576. elif re.search('单价|总金额', sentence_text[_match.span()[0]:_match.span()[1]]):
  2577. notes = '单价'
  2578. elif re.search('[零壹贰叁肆伍陆柒捌玖拾佰仟萬億圆]', entity_text) != None:
  2579. notes = '大写'
  2580. if entity_text[0] == "拾": # 2021/12/16 修正大写金额省略了数字转换错误问题
  2581. entity_text = "壹"+entity_text
  2582. # print("补充备注:notes = 大写")
  2583. if len(unit)>0:
  2584. if unit.find('万')>=0 and len(entity_text.split('.')[0])>=8: # 2021/7/19 修正万元金额过大的情况
  2585. # print('修正单位万元金额过大的情况 金额:', entity_text, '单位:', unit)
  2586. entity_text = str(getUnifyMoney(entity_text) * getMultipleFactor(re.sub("[美日欧]","",unit)[0])/10000)
  2587. unit = '元' # 修正金额后单位 重置为元
  2588. else:
  2589. # print('str(getUnifyMoney(entity_text)*getMultipleFactor(unit[0])):')
  2590. entity_text = str(getUnifyMoney(entity_text)*getMultipleFactor(re.sub("[美日欧]","",unit)[0]))
  2591. else:
  2592. if entity_text.find('万')>=0 and entity_text.split('.')[0].isdigit() and len(entity_text.split('.')[0])>=8:
  2593. entity_text = str(getUnifyMoney(entity_text)/10000)
  2594. # print('修正金额字段含万 过大的情况')
  2595. else:
  2596. entity_text = str(getUnifyMoney(entity_text))
  2597. if science and re.search('^E-?\d+$', science): # 科学计数
  2598. entity_text = str(Decimal(entity_text+science)) if Decimal(entity_text+science) > 100 and Decimal(entity_text+science) < 10000000000 else entity_text # 结果大于100及小于100万才使用科学计算
  2599. if float(entity_text)>100000000000: # float(entity_text)<100 or 2022/3/4 取消最小金额限制
  2600. # print('过滤掉金额:float(entity_text)<100 or float(entity_text)>100000000000', entity_text, unit)
  2601. continue
  2602. if notSure and unit=="" and float(entity_text)>100*10000:
  2603. # print('过滤掉金额 notSure and unit=="" and float(entity_text)>100*10000:', entity_text, unit)
  2604. continue
  2605. _exists = False
  2606. for item in list_sentence_entitys:
  2607. if item.entity_id==entity_id and item.entity_type==entity_type:
  2608. _exists = True
  2609. if (begin_index >=item.begin_index and begin_index<=item.end_index) or (end_index>=item.begin_index and end_index<=item.end_index):
  2610. _exists = True
  2611. if not _exists:
  2612. if float(entity_text)>1:
  2613. if symbol == '-': # 负值金额保留负号
  2614. entity_text = '-'+entity_text
  2615. 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))
  2616. list_sentence_entitys[-1].notes = notes # 2021/7/20 新增金额备注
  2617. list_sentence_entitys[-1].money_unit = unit # 2021/7/20 新增金额备注
  2618. # print('预处理中的 金额:%s, 单位:%s'%(entity_text,unit))
  2619. # print(entity_text,unit,notes)
  2620. else:
  2621. index += 1
  2622. # "联系人"正则补充提取 2021/11/15 新增
  2623. list_person_text = [entity.entity_text for entity in list_sentence_entitys if entity.entity_type=='person']
  2624. error_text = ['交易','机构','教育','项目','公司','中标','开标','截标','监督','政府','国家','中国','技术','投标','传真','网址','电子邮',
  2625. '联系','联系电','联系地','采购代','邮政编','邮政','电话','手机','手机号','联系人','地址','地点','邮箱','邮编','联系方','招标','招标人','代理',
  2626. '代理人','采购','附件','注意','登录','报名','踏勘',"测试",'交货']
  2627. list_person_text = set(list_person_text + error_text)
  2628. re_person = re.compile("联系人[::]([\u4e00-\u9fa5]工)|"
  2629. "联系人[::]([\u4e00-\u9fa5]{2,3})(?=,?联系)|"
  2630. "联系人[::]([\u4e00-\u9fa5]{2,3})(?=[,。;、])"
  2631. )
  2632. list_person = []
  2633. if not in_attachment:
  2634. for match_result in re_person.finditer(sentence_text):
  2635. match_text = match_result.group()
  2636. entity_text = match_text[4:]
  2637. wordOffset_begin = match_result.start() + 4
  2638. wordOffset_end = match_result.end()
  2639. # print(text[wordOffset_begin:wordOffset_end])
  2640. # 排除一些不为人名的实体
  2641. if re.search("^[\u4e00-\u9fa5]{7,}([,。]|$)",sentence_text[wordOffset_begin:wordOffset_begin+20]):
  2642. continue
  2643. if entity_text not in list_person_text and entity_text[:2] not in list_person_text:
  2644. _person = dict()
  2645. _person['body'] = entity_text
  2646. _person['begin_index'] = wordOffset_begin
  2647. _person['end_index'] = wordOffset_end
  2648. list_person.append(_person)
  2649. entity_type = "person"
  2650. for person in list_person:
  2651. begin_index_temp = person['begin_index']
  2652. for j in range(len(list_tokenbegin)):
  2653. if list_tokenbegin[j] == begin_index_temp:
  2654. begin_index = j
  2655. break
  2656. elif list_tokenbegin[j] > begin_index_temp:
  2657. begin_index = j - 1
  2658. break
  2659. index = person['end_index']
  2660. end_index_temp = index
  2661. for j in range(begin_index, len(list_tokenbegin)):
  2662. if list_tokenbegin[j] >= index:
  2663. end_index = j - 1
  2664. break
  2665. entity_id = "%s_%d_%d_%d" % (doc_id, sentence_index, begin_index, end_index)
  2666. entity_text = person['body']
  2667. list_sentence_entitys.append(
  2668. Entity(doc_id, entity_id, entity_text, entity_type, sentence_index, begin_index, end_index,
  2669. begin_index_temp, end_index_temp,in_attachment=in_attachment))
  2670. # 资金来源提取 2020/12/30 新增
  2671. list_moneySource = extract_moneySource(sentence_text)
  2672. entity_type = "moneysource"
  2673. for moneySource in list_moneySource:
  2674. entity_text = moneySource['body']
  2675. if len(entity_text)>50:
  2676. continue
  2677. begin_index_temp = moneySource['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 = moneySource['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))
  2695. # 电子邮箱提取 2021/11/04 新增
  2696. list_email = extract_email(sentence_text)
  2697. entity_type = "email" # 电子邮箱
  2698. for email in list_email:
  2699. begin_index_temp = email['begin_index']
  2700. for j in range(len(list_tokenbegin)):
  2701. if list_tokenbegin[j] == begin_index_temp:
  2702. begin_index = j
  2703. break
  2704. elif list_tokenbegin[j] > begin_index_temp:
  2705. begin_index = j - 1
  2706. break
  2707. index = email['end_index']
  2708. end_index_temp = index
  2709. for j in range(begin_index, len(list_tokenbegin)):
  2710. if list_tokenbegin[j] >= index:
  2711. end_index = j - 1
  2712. break
  2713. entity_id = "%s_%d_%d_%d" % (doc_id, sentence_index, begin_index, end_index)
  2714. entity_text = email['body']
  2715. list_sentence_entitys.append(
  2716. Entity(doc_id, entity_id, entity_text, entity_type, sentence_index, begin_index, end_index,
  2717. begin_index_temp, end_index_temp,in_attachment=in_attachment))
  2718. # 服务期限提取 2020/12/30 新增
  2719. list_servicetime = extract_servicetime(sentence_text)
  2720. entity_type = "serviceTime"
  2721. for servicetime in list_servicetime:
  2722. entity_text = servicetime['body']
  2723. begin_index_temp = servicetime['begin_index']
  2724. for j in range(len(list_tokenbegin)):
  2725. if list_tokenbegin[j] == begin_index_temp:
  2726. begin_index = j
  2727. break
  2728. elif list_tokenbegin[j] > begin_index_temp:
  2729. begin_index = j - 1
  2730. break
  2731. index = servicetime['end_index']
  2732. end_index_temp = index
  2733. for j in range(begin_index, len(list_tokenbegin)):
  2734. if list_tokenbegin[j] >= index:
  2735. end_index = j - 1
  2736. break
  2737. entity_id = "%s_%d_%d_%d" % (doc_id, sentence_index, begin_index, end_index)
  2738. list_sentence_entitys.append(
  2739. Entity(doc_id, entity_id, entity_text, entity_type, sentence_index, begin_index, end_index,
  2740. begin_index_temp, end_index_temp,in_attachment=in_attachment, prob=servicetime["prob"]))
  2741. # 招标方式提取 2020/12/30 新增
  2742. # list_bidway = extract_bidway(sentence_text, )
  2743. # entity_type = "bidway"
  2744. # for bidway in list_bidway:
  2745. # begin_index_temp = bidway['begin_index']
  2746. # end_index_temp = bidway['end_index']
  2747. # begin_index = changeIndexFromWordToWords(tokens, begin_index_temp)
  2748. # end_index = changeIndexFromWordToWords(tokens, end_index_temp)
  2749. # if begin_index is None or end_index is None:
  2750. # continue
  2751. # print(begin_index_temp,end_index_temp,begin_index,end_index)
  2752. # entity_id = "%s_%d_%d_%d" % (doc_id, sentence_index, begin_index, end_index)
  2753. # entity_text = bidway['body']
  2754. # list_sentence_entitys.append(
  2755. # Entity(doc_id, entity_id, entity_text, entity_type, sentence_index, begin_index, end_index,
  2756. # begin_index_temp, end_index_temp))
  2757. # 2021/12/29 新增比率提取
  2758. list_ratio = extract_ratio(sentence_text)
  2759. entity_type = "ratio"
  2760. for ratio in list_ratio:
  2761. # print("ratio", ratio)
  2762. begin_index_temp = ratio['begin_index']
  2763. for j in range(len(list_tokenbegin)):
  2764. if list_tokenbegin[j] == begin_index_temp:
  2765. begin_index = j
  2766. break
  2767. elif list_tokenbegin[j] > begin_index_temp:
  2768. begin_index = j - 1
  2769. break
  2770. index = ratio['end_index']
  2771. end_index_temp = index
  2772. for j in range(begin_index, len(list_tokenbegin)):
  2773. if list_tokenbegin[j] >= index:
  2774. end_index = j - 1
  2775. break
  2776. entity_id = "%s_%d_%d_%d" % (doc_id, sentence_index, begin_index, end_index)
  2777. entity_text = ratio['body']
  2778. ratio_value = (ratio['value'],ratio['type'])
  2779. _entity = Entity(doc_id, entity_id, entity_text, entity_type, sentence_index, begin_index, end_index,
  2780. begin_index_temp, end_index_temp,in_attachment=in_attachment)
  2781. _entity.ratio_value = ratio_value
  2782. list_sentence_entitys.append(_entity)
  2783. list_sentence_entitys.sort(key=lambda x:x.begin_index)
  2784. list_entitys_temp = list_entitys_temp+list_sentence_entitys
  2785. # 补充ner模型未识别全的company/org实体
  2786. for sentence_index in range(len(list_sentence)):
  2787. sentence_text = list_sentence[sentence_index].sentence_text
  2788. tokens = list_sentence[sentence_index].tokens
  2789. doc_id = list_sentence[sentence_index].doc_id
  2790. in_attachment = list_sentence[sentence_index].in_attachment
  2791. list_tokenbegin = []
  2792. begin = 0
  2793. for i in range(0, len(tokens)):
  2794. list_tokenbegin.append(begin)
  2795. begin += len(str(tokens[i]))
  2796. list_tokenbegin.append(begin + 1)
  2797. add_sentence_entitys = []
  2798. company_dict = sorted(list(company_dict),key=lambda x:len(x[1]),reverse=True)
  2799. for company_type,company_text in company_dict:
  2800. begin_index_list = findAllIndex(company_text,sentence_text)
  2801. for begin_index in begin_index_list:
  2802. is_continue = False
  2803. for t_begin,t_end in list(company_index[sentence_index]):
  2804. if begin_index>=t_begin and begin_index+len(company_text)<=t_end:
  2805. is_continue = True
  2806. break
  2807. if not is_continue:
  2808. add_sentence_entitys.append((begin_index,begin_index+len(company_text),company_type,company_text))
  2809. company_index[sentence_index].add((begin_index,begin_index+len(company_text)))
  2810. else:
  2811. continue
  2812. for ner_entity in add_sentence_entitys:
  2813. begin_index_temp = ner_entity[0]
  2814. end_index_temp = ner_entity[1]
  2815. entity_type = ner_entity[2]
  2816. entity_text = ner_entity[3]
  2817. if entity_type in ["org","company"] and not isLegalEnterprise(entity_text):
  2818. continue
  2819. for j in range(len(list_tokenbegin)):
  2820. if list_tokenbegin[j]==begin_index_temp:
  2821. begin_index = j
  2822. break
  2823. elif list_tokenbegin[j]>begin_index_temp:
  2824. begin_index = j-1
  2825. break
  2826. begin_index_temp += len(str(entity_text))
  2827. for j in range(begin_index,len(list_tokenbegin)):
  2828. if list_tokenbegin[j]>=begin_index_temp:
  2829. end_index = j-1
  2830. break
  2831. entity_id = "%s_%d_%d_%d"%(doc_id,sentence_index,begin_index,end_index)
  2832. #去掉标点符号
  2833. entity_text = re.sub("[,,。:!&@$\*]","",entity_text)
  2834. entity_text = entity_text.replace("(","(").replace(")",")") if isinstance(entity_text,str) else entity_text
  2835. 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))
  2836. list_entitys_temp.sort(key=lambda x:(x.sentence_index,x.begin_index))
  2837. list_entitys.append(list_entitys_temp)
  2838. return list_entitys
  2839. def union_result(codeName,prem):
  2840. '''
  2841. @summary:模型的结果拼成字典
  2842. @param:
  2843. codeName:编号名称模型的结果字典
  2844. prem:拿到属性的角色的字典
  2845. @return:拼接起来的字典
  2846. '''
  2847. result = []
  2848. assert len(codeName)==len(prem)
  2849. for item_code,item_prem in zip(codeName,prem):
  2850. result.append(dict(item_code,**item_prem))
  2851. return result
  2852. def persistenceData(data):
  2853. '''
  2854. @summary:将中间结果保存到数据库-线上生产的时候不需要执行
  2855. '''
  2856. import psycopg2
  2857. conn = psycopg2.connect(dbname="BiddingKG",user="postgres",password="postgres",host="192.168.2.101")
  2858. cursor = conn.cursor()
  2859. for item_index in range(len(data)):
  2860. item = data[item_index]
  2861. doc_id = item[0]
  2862. dic = item[1]
  2863. code = dic['code']
  2864. name = dic['name']
  2865. prem = dic['prem']
  2866. if len(code)==0:
  2867. code_insert = ""
  2868. else:
  2869. code_insert = ";".join(code)
  2870. prem_insert = ""
  2871. for item in prem:
  2872. for x in item:
  2873. if isinstance(x, list):
  2874. if len(x)>0:
  2875. for x1 in x:
  2876. prem_insert+="/".join(x1)+","
  2877. prem_insert+="$"
  2878. else:
  2879. prem_insert+=str(x)+"$"
  2880. prem_insert+=";"
  2881. sql = " insert into predict_validation(doc_id,code,name,prem) values('"+doc_id+"','"+code_insert+"','"+name+"','"+prem_insert+"')"
  2882. cursor.execute(sql)
  2883. conn.commit()
  2884. conn.close()
  2885. def persistenceData1(list_entitys,list_sentences):
  2886. '''
  2887. @summary:将中间结果保存到数据库-线上生产的时候不需要执行
  2888. '''
  2889. import psycopg2
  2890. conn = psycopg2.connect(dbname="BiddingKG",user="postgres",password="postgres",host="192.168.2.101")
  2891. cursor = conn.cursor()
  2892. for list_entity in list_entitys:
  2893. for entity in list_entity:
  2894. if entity.values is not None:
  2895. 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)+")"
  2896. else:
  2897. 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)+")"
  2898. cursor.execute(sql)
  2899. for list_sentence in list_sentences:
  2900. for sentence in list_sentence:
  2901. str_tokens = "["
  2902. for item in sentence.tokens:
  2903. str_tokens += "'"
  2904. if item=="'":
  2905. str_tokens += "''"
  2906. else:
  2907. str_tokens += item
  2908. str_tokens += "',"
  2909. str_tokens = str_tokens[:-1]+"]"
  2910. sql = " insert into predict_sentences(doc_id,sentence_index,tokens) values('"+sentence.doc_id+"',"+str(sentence.sentence_index)+",array"+str_tokens+")"
  2911. cursor.execute(sql)
  2912. conn.commit()
  2913. conn.close()
  2914. def _handle(item,result_queue):
  2915. dochtml = item["dochtml"]
  2916. docid = item["docid"]
  2917. list_innerTable = tableToText(BeautifulSoup(dochtml,"lxml"))
  2918. flag = False
  2919. if list_innerTable:
  2920. flag = True
  2921. for table in list_innerTable:
  2922. result_queue.put({"docid":docid,"json_table":json.dumps(table,ensure_ascii=False)})
  2923. def getPredictTable():
  2924. filename = "D:\Workspace2016\DataExport\data\websouce_doc.csv"
  2925. import pandas as pd
  2926. import json
  2927. from BiddingKG.dl.common.MultiHandler import MultiHandler,Queue
  2928. df = pd.read_csv(filename)
  2929. df_data = {"json_table":[],"docid":[]}
  2930. _count = 0
  2931. _sum = len(df["docid"])
  2932. task_queue = Queue()
  2933. result_queue = Queue()
  2934. _index = 0
  2935. for dochtml,docid in zip(df["dochtmlcon"],df["docid"]):
  2936. task_queue.put({"docid":docid,"dochtml":dochtml,"json_table":None})
  2937. _index += 1
  2938. mh = MultiHandler(task_queue=task_queue,task_handler=_handle,result_queue=result_queue,process_count=5,thread_count=1)
  2939. mh.run()
  2940. while True:
  2941. try:
  2942. item = result_queue.get(block=True,timeout=1)
  2943. df_data["docid"].append(item["docid"])
  2944. df_data["json_table"].append(item["json_table"])
  2945. except Exception as e:
  2946. print(e)
  2947. break
  2948. df_1 = pd.DataFrame(df_data)
  2949. df_1.to_csv("../form/websource_67000_table.csv",columns=["docid","json_table"])
  2950. if __name__=="__main__":
  2951. '''
  2952. import glob
  2953. for file in glob.glob("C:\\Users\\User\\Desktop\\test\\*.html"):
  2954. file_txt = str(file).replace("html","txt")
  2955. with codecs.open(file_txt,"a+",encoding="utf8") as f:
  2956. f.write("\n================\n")
  2957. content = codecs.open(file,"r",encoding="utf8").read()
  2958. f.write(segment(tableToText(BeautifulSoup(content,"lxml"))))
  2959. '''
  2960. # content = codecs.open("C:\\Users\\User\\Desktop\\2.html","r",encoding="utf8").read()
  2961. # print(segment(tableToText(BeautifulSoup(content,"lxml"))))
  2962. # getPredictTable()
  2963. with open('D:/138786703.html', 'r', encoding='utf-8') as f:
  2964. sourceContent = f.read()
  2965. # article_processed = segment(tableToText(BeautifulSoup(sourceContent, "lxml")))
  2966. # print(article_processed)
  2967. list_articles, list_sentences, list_entitys, _cost_time = get_preprocessed([['doc_id', sourceContent, "", "", '', '2021-02-01']], useselffool=True)
  2968. for entity in list_entitys[0]:
  2969. print(entity.entity_type, entity.entity_text)