Preprocessing.py 115 KB

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