Preprocessing.py 103 KB

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