Preprocessing.py 138 KB

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