Preprocessing.py 125 KB

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