Preprocessing.py 158 KB

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