Preprocessing.py 100 KB

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