Preprocessing.py 150 KB

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