Preprocessing.py 146 KB

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