Preprocessing.py 108 KB

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