getAttributes.py 208 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551
  1. from BiddingKG.dl.common.Utils import findAllIndex,debug,timeFormat,getCurrent_date,API_URL,uniform_package_name
  2. from BiddingKG.dl.interface.Entitys import PREM,Role,Entity
  3. from decimal import Decimal
  4. import re
  5. import copy
  6. import math
  7. import pandas as pd
  8. import os
  9. from scipy.optimize import linear_sum_assignment
  10. from BiddingKG.dl.interface.Entitys import Match
  11. import numpy as np
  12. def getTheRole(entity,role_list):
  13. '''
  14. @summary:根据实体名称拿到index
  15. @param:
  16. entity:实体名称
  17. role_list:角色list
  18. @return:该实体所在下标
  19. '''
  20. for role_index in range(len(role_list)):
  21. if entity in role_list[role_index]:
  22. return role_index
  23. return None
  24. dict_role_id = {"0":"tenderee",
  25. "1":"agency",
  26. "2":"win_tenderer",
  27. "3":"second_tenderer",
  28. "4":"third_tenderer"}
  29. role2id_dict = {"tenderee":0,
  30. "agency":1,
  31. "win_tenderer":2,
  32. "second_tenderer":3,
  33. "third_tenderer":4}
  34. def getPackage(packageList,sentence_index,begin_index,roleid,MAX_DIS=None,DIRECT=None):
  35. '''
  36. @param:
  37. packageList:文章的包的信息,包号-sent_index-词偏移-字偏移-[[前作用域句子,句内偏移],[后作用域句子,句内偏移]]-匹配集合
  38. sentence_index:实体所在的句子
  39. begin_index:实体所在句子的起始位置
  40. @return:公司实体所属的包
  41. @summary: 优化多标段,确定标段作用域之后,寻找作用域包含该实体的所有包,从前往后找到一个还没有该roleid的包返回,若找到的包都有roleid,则返回第一个,若没有找到包,返回None
  42. '''
  43. '''
  44. if len(packageList)==0:
  45. return None
  46. before_index = None
  47. after_index = None
  48. equal_index = None
  49. equal_count = 0
  50. for pack_index in range(len(packageList)):
  51. if packageList[pack_index][1]>sentence_index and after_index is None:
  52. after_index = pack_index
  53. if packageList[pack_index][1]<sentence_index:
  54. before_index = pack_index
  55. if packageList[pack_index][1]==sentence_index and equal_index is None:
  56. equal_index = pack_index
  57. #当前句子和之前句子未找到包
  58. if before_index is None and equal_index is None:
  59. return None
  60. else:
  61. if after_index is None:
  62. end_index = len(packageList)
  63. else:
  64. end_index = after_index
  65. #只在当前句子找到一个包号
  66. if end_index-max((before_index if before_index is not None else -1,equal_index if equal_index is not None else -1))==1:
  67. return packageList[end_index-1][0]
  68. else:
  69. for i in range(max((before_index if before_index is not None else -1,equal_index if equal_index is not None else -1)),end_index):
  70. if packageList[i][2]>int(begin_index):
  71. if packageList[i-1][4]:
  72. return packageList[i-1][0]
  73. else:
  74. if packageList[i][4]:
  75. return packageList[i-1][0]
  76. else:
  77. return packageList[i][0]
  78. return packageList[end_index-1][0]
  79. '''
  80. if len(packageList)==0:
  81. return None,False
  82. list_legalPack = []
  83. for pack_index in range(len(packageList)):
  84. if DIRECT=="L" and (packageList[pack_index]["sentence_index"]>sentence_index or (packageList[pack_index]["sentence_index"]==sentence_index and packageList[pack_index]["offsetWords_begin"]>begin_index)):
  85. continue
  86. if DIRECT=="R" and (packageList[pack_index]["sentence_index"]<sentence_index or (packageList[pack_index]["sentence_index"]==sentence_index and packageList[pack_index]["offsetwords_begin"]<begin_index)):
  87. continue
  88. if (packageList[pack_index]["scope"][0][0]<sentence_index or (packageList[pack_index]["scope"][0][0]==sentence_index and packageList[pack_index]["scope"][0][1]<=begin_index)) and (packageList[pack_index]["scope"][1][0]>sentence_index or (packageList[pack_index]["scope"][1][0]==sentence_index and packageList[pack_index]["scope"][1][1]>=begin_index)):
  89. if MAX_DIS is not None:
  90. if abs(sentence_index-packageList[pack_index]["sentence_index"])<=MAX_DIS:
  91. list_legalPack.append(pack_index)
  92. else:
  93. list_legalPack.append(pack_index)
  94. # if (packageList[pack_index]["scope"][0][0] < sentence_index
  95. # or (packageList[pack_index]["scope"][0][0] == sentence_index
  96. # and packageList[pack_index]["scope"][0][1] <= begin_index))
  97. # and (packageList[pack_index]["scope"][1][0] > sentence_index
  98. # or (packageList[pack_index]["scope"][1][0] == sentence_index
  99. # and packageList[pack_index]["scope"][1][1] >= begin_index)):
  100. # pass
  101. _flag = True
  102. for _index in list_legalPack:
  103. if roleid in packageList[_index]["hit"]:
  104. continue
  105. else:
  106. _flag = False
  107. packageList[_index]["hit"].add(roleid)
  108. return packageList[_index]["pointer"],_flag
  109. if len(list_legalPack)>0:
  110. return packageList[0]["pointer"],_flag
  111. return None,False
  112. #生成合法的组合
  113. def get_legal_comba(list_entity,dict_role_combination):
  114. #拿到一个包中所有合法的组合
  115. def circle_package(_dict_legal_combination):
  116. list_dict_role_first = []
  117. for _role in _dict_legal_combination:
  118. if len(list_dict_role_first)==0:
  119. for _entity in _dict_legal_combination[_role]:
  120. if _entity !="":
  121. list_dict_role_first.append({_role:_entity})
  122. else:
  123. list_dict_role_after = []
  124. _find_count = 0
  125. for _entity in _dict_legal_combination[_role]:
  126. if _entity !="":
  127. for _dict in list_dict_role_first:
  128. _flag = True
  129. for _key1 in _dict:
  130. if _entity==_dict[_key1]:
  131. #修改为招标人和代理人可以为同一个
  132. if str(_key1) in ["0","1"] and str(_role) in ["0","1"]:
  133. _flag = True
  134. else:
  135. _flag = False
  136. if _flag:
  137. _find_count += 1
  138. _new_dict = copy.copy(_dict)
  139. _new_dict[_role] = _entity
  140. if len(list_dict_role_after)>100000:
  141. break
  142. list_dict_role_after.append(_new_dict)
  143. else:
  144. # 2021/5/25 update,同一实体(entity_text)不同角色
  145. if len(list_dict_role_after) > 100000:
  146. break
  147. for _dict in list_dict_role_first:
  148. for _key1 in _dict:
  149. if _entity == _dict[_key1]:
  150. _new_dict = copy.copy(_dict)
  151. _new_dict.pop(_key1)
  152. _new_dict[_role] = _entity
  153. list_dict_role_after.append({_role:_entity})
  154. if len(list_dict_role_after)==0:
  155. pass
  156. else:
  157. list_dict_role_first.extend(list_dict_role_after)
  158. return list_dict_role_first
  159. def recursive_package(_dict_legal_combination,set_legal_entity,dict_one_selution,list_all_selution):
  160. last_layer = False
  161. #若是空组合则放回空
  162. if len(_dict_legal_combination.keys())==0:
  163. return []
  164. #递归到最后一层则修改状态
  165. if len(_dict_legal_combination.keys())==1:
  166. last_layer = True
  167. #取一个角色开始进行遍历
  168. _key_role = list(_dict_legal_combination.keys())[0]
  169. for item in _dict_legal_combination[_key_role]:
  170. copy_dict_one_selution = copy.copy(dict_one_selution)
  171. copy_dict_legal_combination = {}
  172. copy_set_legal_entity = copy.copy(set_legal_entity)
  173. #复制余下的所有角色,进行下一轮递归
  174. for _key in _dict_legal_combination.keys():
  175. if _key!=_key_role:
  176. copy_dict_legal_combination[_key] = _dict_legal_combination[_key]
  177. #修改为招标人和代理人可以为同一个
  178. if item !="":
  179. _flag = True
  180. if str(_key_role) in ["0","1"]:
  181. for _key_flag in copy_dict_one_selution:
  182. if _key_flag not in ["0","1"] and copy_dict_one_selution[_key_flag]==item:
  183. _flag = False
  184. else:
  185. for _key_flag in copy_dict_one_selution:
  186. if copy_dict_one_selution[_key_flag]==item:
  187. _flag = False
  188. if _flag:
  189. copy_dict_one_selution[_key_role] = item
  190. '''
  191. if item not in copy_set_legal_entity:
  192. if item !="":
  193. copy_dict_one_selution[_key_role] = item
  194. '''
  195. copy_set_legal_entity.add(item)
  196. if last_layer:
  197. list_all_selution.append(copy_dict_one_selution)
  198. else:
  199. recursive_package(copy_dict_legal_combination,copy_set_legal_entity,copy_dict_one_selution,list_all_selution)
  200. #递归匹配各个包的结果
  201. def recursive_packages(_dict_legal_combination,dict_one_selution,list_all_selution):
  202. last_layer = False
  203. if len(_dict_legal_combination.keys())==0:
  204. return []
  205. if len(_dict_legal_combination.keys())==1:
  206. last_layer = True
  207. _key_pack = list(_dict_legal_combination.keys())[0]
  208. for item in _dict_legal_combination[_key_pack]:
  209. copy_dict_one_selution = copy.copy(dict_one_selution)
  210. copy_dict_legal_combination = {}
  211. for _key in _dict_legal_combination.keys():
  212. if _key!=_key_pack:
  213. copy_dict_legal_combination[_key] = _dict_legal_combination[_key]
  214. for _key_role in item.keys():
  215. copy_dict_one_selution[_key_pack+"$$"+_key_role] = item[_key_role]
  216. if last_layer:
  217. list_all_selution.append(copy_dict_one_selution)
  218. else:
  219. recursive_packages(copy_dict_legal_combination,copy_dict_one_selution,list_all_selution)
  220. return list_all_selution
  221. #循环获取所有包组合
  222. def circle_pageages(_dict_legal_combination):
  223. list_all_selution = []
  224. for _key_pack in _dict_legal_combination.keys():
  225. list_key_selution = []
  226. for item in _dict_legal_combination[_key_pack]:
  227. _dict = dict()
  228. for _key_role in item.keys():
  229. _dict[_key_pack+"$$"+_key_role] = item[_key_role]
  230. list_key_selution.append(_dict)
  231. if len(list_all_selution)==0:
  232. list_all_selution = list_key_selution
  233. else:
  234. _list_all_selution = []
  235. for item_1 in list_all_selution:
  236. for item_2 in list_key_selution:
  237. _list_all_selution.append(dict(item_1,**item_2))
  238. list_all_selution = _list_all_selution
  239. return list_all_selution
  240. #拿到各个包解析之后的结果
  241. _dict_legal_combination = {}
  242. for packageName in dict_role_combination.keys():
  243. _list_all_selution = []
  244. # recursive_package(dict_role_combination[packageName], set(), {}, _list_all_selution)
  245. _list_all_selution = circle_package(dict_role_combination[packageName])
  246. '''
  247. # print("===1")
  248. # print(packageName)
  249. for item in _list_all_selution:
  250. # print(item)
  251. # print("===2")
  252. '''
  253. #去除包含子集
  254. list_all_selution_simple = []
  255. _list_set_all_selution = []
  256. for item_selution in _list_all_selution:
  257. item_set_selution = set()
  258. for _key in item_selution.keys():
  259. item_set_selution.add((_key,item_selution[_key]))
  260. _list_set_all_selution.append(item_set_selution)
  261. if len(_list_set_all_selution)>1000:
  262. _dict_legal_combination[packageName] = _list_all_selution
  263. continue
  264. for i in range(len(_list_set_all_selution)):
  265. be_included = False
  266. for j in range(len(_list_set_all_selution)):
  267. if i!=j:
  268. if len(set(_list_set_all_selution[i])&set(_list_set_all_selution[j]))==len(_list_set_all_selution[i]) and len(_list_set_all_selution[i])!=len(_list_set_all_selution[j]):
  269. be_included = True
  270. if not be_included:
  271. list_all_selution_simple.append(_list_all_selution[i])
  272. _dict_legal_combination[packageName] = list_all_selution_simple
  273. _list_final_comba = []
  274. #对各个包的结果进行排列组合
  275. _comba_count = 1
  276. for _key in _dict_legal_combination.keys():
  277. _comba_count *= len(_dict_legal_combination[_key])
  278. #如果过大,则每个包只取概率最大的那个
  279. dict_pack_entity_prob = get_dict_entity_prob(list_entity)
  280. if _comba_count>250:
  281. new_dict_legal_combination = dict()
  282. for _key_pack in _dict_legal_combination.keys():
  283. MAX_PROB = -1000
  284. _MAX_PROB_COMBA = None
  285. for item in _dict_legal_combination[_key_pack]:
  286. # print(_key_pack,item)
  287. _dict = dict()
  288. for _key in item.keys():
  289. _dict[str(_key_pack)+"$$"+str(_key)] = item[_key]
  290. _prob = getSumExpectation(dict_pack_entity_prob, _dict)
  291. if _prob>MAX_PROB:
  292. MAX_PROB = _prob
  293. _MAX_PROB_COMBA = [item]
  294. if _MAX_PROB_COMBA is not None:
  295. new_dict_legal_combination[_key_pack] = _MAX_PROB_COMBA
  296. _dict_legal_combination = new_dict_legal_combination
  297. #recursive_packages(_dict_legal_combination, {}, _list_final_comba)
  298. _list_final_comba = circle_pageages(_dict_legal_combination)
  299. #除了Project包(招标人和代理人),其他包是不会有冲突的
  300. #查看是否有一个实体出现在了Project包和其他包中,如有,要进行裁剪
  301. _list_real_comba = []
  302. for dict_item in _list_final_comba:
  303. set_project = set()
  304. set_other = set()
  305. for _key in list(dict_item.keys()):
  306. if _key.split("$$")[0]=="Project":
  307. set_project.add(dict_item[_key])
  308. else:
  309. set_other.add(dict_item[_key])
  310. set_common = set_project&set_other
  311. if len(set_common)>0:
  312. dict_project = {}
  313. dict_not_project = {}
  314. for _key in list(dict_item.keys()):
  315. if dict_item[_key] in set_common:
  316. if str(_key.split("$$")[0])=="Project":
  317. dict_project[_key] = dict_item[_key]
  318. else:
  319. dict_not_project[_key] = dict_item[_key]
  320. else:
  321. dict_project[_key] = dict_item[_key]
  322. dict_not_project[_key] = dict_item[_key]
  323. _list_real_comba.append(dict_project)
  324. _list_real_comba.append(dict_not_project)
  325. else:
  326. _list_real_comba.append(dict_item)
  327. return _list_real_comba
  328. def get_dict_entity_prob(list_entity,on_value=0.5):
  329. dict_pack_entity_prob = {}
  330. for in_attachment in [False,True]:
  331. identified_role = []
  332. if in_attachment==True:
  333. identified_role = [value[0] for value in dict_pack_entity_prob.values()]
  334. for entity in list_entity:
  335. if entity.entity_type in ['org','company'] and entity.in_attachment==in_attachment:
  336. values = entity.values
  337. role_prob = float(values[int(entity.label)])
  338. _key = entity.packageName+"$$"+str(entity.label)
  339. if role_prob>=on_value and str(entity.label)!="5":
  340. _key_prob = _key+"$text$"+entity.entity_text
  341. if in_attachment == True:
  342. role_prob = 0.8 if role_prob>0.8 else role_prob #附件的概率修改低点
  343. if entity.entity_text in identified_role:
  344. continue
  345. if _key_prob in dict_pack_entity_prob:
  346. # new_prob = role_prob+dict_pack_entity_prob[_key_prob][1] if role_prob>0.9 else max(role_prob, dict_pack_entity_prob[_key_prob][1])
  347. # dict_pack_entity_prob[_key_prob] = [entity.entity_text, new_prob] #公司同角色多次出现概率累计
  348. if role_prob>dict_pack_entity_prob[_key_prob][1]:
  349. dict_pack_entity_prob[_key_prob] = [entity.entity_text,role_prob]
  350. else:
  351. dict_pack_entity_prob[_key_prob] = [entity.entity_text,role_prob]
  352. return dict_pack_entity_prob
  353. #计算合计期望
  354. def getSumExpectation(dict_pack_entity_prob,combination,on_value=0.5):
  355. '''
  356. expect = 0
  357. for entity in list_entity:
  358. if entity.entity_type in ['org','company']:
  359. values = entity.values
  360. role_prob = float(values[int(entity.label)])
  361. _key = entity.packageName+"$$"+str(entity.label)
  362. if role_prob>on_value and str(entity.label)!="5":
  363. if _key in combination.keys() and combination[_key]==entity.entity_text:
  364. expect += math.pow(role_prob,4)
  365. else:
  366. expect -= math.pow(role_prob,4)
  367. '''
  368. #修改为同一个实体只取对应包-角色的最大的概率值
  369. expect = 0
  370. dict_entity_prob = {}
  371. for _key_pack_entity in dict_pack_entity_prob:
  372. _key_pack = _key_pack_entity.split("$text$")[0]
  373. role_prob = dict_pack_entity_prob[_key_pack_entity][1]
  374. if _key_pack in combination.keys() and combination[_key_pack]==dict_pack_entity_prob[_key_pack_entity][0]:
  375. if _key_pack_entity in dict_entity_prob.keys():
  376. if dict_entity_prob[_key_pack_entity]<role_prob:
  377. dict_entity_prob[_key_pack_entity] = role_prob
  378. else:
  379. dict_entity_prob[_key_pack_entity] = role_prob
  380. else:
  381. if _key_pack_entity in dict_entity_prob.keys():
  382. if dict_entity_prob[_key_pack_entity]>-role_prob:
  383. dict_entity_prob[_key_pack_entity] = -role_prob
  384. else:
  385. dict_entity_prob[_key_pack_entity] = -role_prob
  386. # for entity in list_entity:
  387. # if entity.entity_type in ['org','company']:
  388. # values = entity.values
  389. # role_prob = float(values[int(entity.label)])
  390. # _key = entity.packageName+"$$"+str(entity.label)
  391. # if role_prob>=on_value and str(entity.label)!="5":
  392. # if _key in combination.keys() and combination[_key]==entity.entity_text:
  393. # _key_prob = _key+entity.entity_text
  394. # if _key_prob in dict_entity_prob.keys():
  395. # if dict_entity_prob[_key_prob]<role_prob:
  396. # dict_entity_prob[_key_prob] = role_prob
  397. # else:
  398. # dict_entity_prob[_key_prob] = role_prob
  399. # else:
  400. # _key_prob = _key+entity.entity_text
  401. # if _key_prob in dict_entity_prob.keys():
  402. # if dict_entity_prob[_key_prob]>-role_prob:
  403. # dict_entity_prob[_key_prob] = -role_prob
  404. # else:
  405. # dict_entity_prob[_key_prob] = -role_prob
  406. for _key in dict_entity_prob.keys():
  407. symbol = 1 if dict_entity_prob[_key]>0 else -1
  408. expect += symbol*math.pow(dict_entity_prob[_key],2)
  409. return expect
  410. def getRoleList(list_sentence,list_entity,on_value = 0.5):
  411. '''
  412. @summary: 搜索树,得到所有不矛盾的角色组合,取合计期望值最大的作为结果返回
  413. @param:
  414. list_sentence:文章所有的sentence
  415. list_entity:文章所有的实体
  416. on_value:概率阈值
  417. @return:文章的角色list
  418. '''
  419. pack = getPackagesFromArticle(list_sentence,list_entity)
  420. if pack is None:
  421. return None
  422. PackageList,PackageSet,dict_PackageCode = pack
  423. #拿到所有可能的情况
  424. dict_role_combination = {}
  425. # print(PackageList)
  426. #拿到各个实体的packageName,packageCode
  427. for entity in list_entity:
  428. if entity.entity_type in ['org','company']:
  429. #限制附件里角色values[label]最大概率prob
  430. max_prob = 0.85
  431. if str(entity.label)!="5" and entity.in_attachment:
  432. if entity.values[entity.label]>max_prob:
  433. entity.values[entity.label] = max_prob
  434. #过滤掉字数小于3个的实体
  435. if len(entity.entity_text)<=3:
  436. continue
  437. values = entity.values
  438. role_prob = float(values[int(entity.label)])
  439. if role_prob>=on_value and str(entity.label)!="5":
  440. if str(entity.label) in ["0","1"]:
  441. packageName = "Project"
  442. else:
  443. if len(PackageSet)>0:
  444. packagePointer,_ = getPackage(PackageList,entity.sentence_index,entity.begin_index,"role-"+str(entity.label))
  445. if packagePointer is None:
  446. #continue
  447. packageName = "Project"
  448. # print(entity.entity_text, packageName,entity.sentence_index,entity.begin_index)
  449. else:
  450. #add pointer_pack
  451. entity.pointer_pack = packagePointer
  452. packageName = packagePointer.entity_text
  453. # print(entity.entity_text, packageName)
  454. else:
  455. packageName = "Project"
  456. find_flag = False
  457. if packageName in dict_PackageCode.keys():
  458. packageCode = dict_PackageCode[packageName]
  459. else:
  460. packageCode = ""
  461. entity.packageCode = packageCode
  462. role_name = dict_role_id.get(str(entity.label))
  463. entity.roleName = role_name
  464. entity.packageName = packageName
  465. if entity.packageName in dict_role_combination.keys():
  466. if str(entity.label) in dict_role_combination[entity.packageName].keys():
  467. dict_role_combination[entity.packageName][str(entity.label)].add(entity.entity_text)
  468. else:
  469. dict_role_combination[entity.packageName][str(entity.label)] = set([entity.entity_text])
  470. else:
  471. dict_role_combination[entity.packageName] = {}
  472. #初始化空值
  473. roleIds = [0,1,2,3,4]
  474. for _roleId in roleIds:
  475. dict_role_combination[entity.packageName][str(_roleId)] = set([""])
  476. dict_role_combination[entity.packageName][str(entity.label)].add(entity.entity_text)
  477. list_real_comba = get_legal_comba(list_entity,dict_role_combination)
  478. # print("===role_combination",dict_role_combination)
  479. # print("== real_comba",list_real_comba)
  480. #拿到最大期望值的组合
  481. max_index = 0
  482. max_expect = -100
  483. _index = 0
  484. dict_pack_entity_prob = get_dict_entity_prob(list_entity)
  485. for item_combination in list_real_comba:
  486. expect = getSumExpectation(dict_pack_entity_prob, item_combination)
  487. if expect>max_expect:
  488. max_index = _index
  489. max_expect = expect
  490. _index += 1
  491. RoleList = []
  492. RoleSet = set()
  493. if len(list_real_comba)>0:
  494. for _key in list_real_comba[max_index].keys():
  495. packageName = _key.split("$$")[0]
  496. label = _key.split("$$")[1]
  497. role_name = dict_role_id.get(str(label))
  498. entity_text = list_real_comba[max_index][_key]
  499. if packageName in dict_PackageCode.keys():
  500. packagecode = dict_PackageCode.get(packageName)
  501. else:
  502. packagecode = ""
  503. RoleList.append(PREM(packageName,packagecode,role_name,entity_text,0,0,0.0,[]))
  504. RoleSet.add(entity_text)
  505. #根据最优树来修正list_entity中角色对包的连接
  506. for _entity in list_entity:
  507. if _entity.pointer_pack is not None:
  508. _pack_name = _entity.pointer_pack.entity_text
  509. _find_flag = False
  510. for _prem in RoleList:
  511. if _prem.packageName==_pack_name and _prem.entity_text==_entity.entity_text:
  512. _find_flag = True
  513. if not _find_flag:
  514. _entity.pointer_pack = None
  515. return RoleList,RoleSet,PackageList,PackageSet
  516. def getPackageScopePattern():
  517. '''
  518. @summary: 获取包的作用域关键词
  519. '''
  520. df = pd.read_excel(os.path.dirname(__file__)+"/end.xls")
  521. pattern = "("
  522. for item in df["list_word"]:
  523. item = str(item).replace("(","\(").replace(")","\)").replace(".","\.").replace("[","\[").replace("]","\]").replace("-","\-")
  524. pattern += item+"|"
  525. pattern = pattern[:-1]+")[::是为]|业绩.{,30}标段[0-9A-Za-z一二三四五六七八九十]{0,3}"
  526. return pattern
  527. pattern_packageScope = getPackageScopePattern()
  528. def getPackagesFromArticle_backup(list_sentence,list_entity):
  529. '''
  530. @param:
  531. list_sentence:文章的句子list
  532. @summary: 将包的信息插入list_entity中
  533. @return: type:list if [包号,句子index,词偏移,标段号] meaning:文章的包/标段信息
  534. '''
  535. if len(list_sentence)==0:
  536. return None
  537. list_sentence.sort(key=lambda x:x.sentence_index)
  538. PackageList = []
  539. PackageList_scope = []
  540. PackageSet = set()
  541. dict_packageCode = dict()
  542. package_name_pattern = re.compile("((标[段号的包]|分包)的?(名[称单]?|包名))[::]?([^::]{3,30}?),{1}")
  543. package_N_name_pattern = re.compile("(([^承]|^)分?包|标段|标包|标|包|包组|子项目|包件|项目类型)编?号?[::]?[\((]?([0-9A-Za-z一二三四五六七八九十ⅠⅡⅢⅣⅤⅥⅦ]){1,2},{1}")
  544. package_number_pattern = re.compile("(((([^承]|^)包|标[段号的包]|分?包|包组|包件)编?号?|子项目|项目类型)[::]?[0-9A-Za-z一二三四五六七八九十ⅠⅡⅢⅣⅤⅥⅦ]{1,4}[^\.])[^至]?|([^\.]?第[ⅠⅡⅢⅣⅤⅥⅦ0-9A-Za-z一二三四五六七八九十]{1,4}(包号|标[段号的包]|分?包))|([^\.]?[ⅠⅡⅢⅣⅤⅥⅦ0-9A-Za-z一二三四五六七八九十]{1,4}(标[段号的包]))") # 第? 去掉问号 修复 纯木浆8包/箱复印 这种作为包号
  545. # other_package_pattern = re.compile('(项目名称|物资名称|设备名称|场次名称|标段名称)[::](.{,20}?)(,|项目)') # 新正则识别标段
  546. other_package_pattern = re.compile('((项目|物资|设备|场次|标段|标的|产品)(名称)?)[::]([^,。]{2,50}?)[,。]') # # 2020/11/23 大网站规则 调整 package_N_name_pattern, package_N_name_pattern 中的项目 改为 子项目
  547. win_tenderer_pattern = re.compile('(中标候?选?人|供应商)(名称)?[::](.{2,25})[,。]') # 2020/11/23 大网站规则 调整
  548. model_pattern = re.compile('(型号|序号)[::]([^,。]{2,20})[,。]') # 2020/11/23 大网站规则 调整
  549. number_pattern = re.compile("[0-9A-Za-z一二三四五六七八九十ⅠⅡⅢⅣⅤⅥⅦ]{1,4}")
  550. package_code_pattern = re.compile("(?:编号[::]?\s*)([-\dA-Za-z\(\)]+)")
  551. # 纯数字类型的包号统一,例如:'01','1'
  552. re_digital = re.compile("^\d+$")
  553. def changeIndexFromWordToWords(tokens,word_index):
  554. '''
  555. @summary:转换某个字的字偏移为词偏移
  556. '''
  557. before_index = 0
  558. after_index = 0
  559. for i in range(len(tokens)):
  560. after_index = after_index+len(tokens[i])
  561. if before_index<=word_index and after_index>=word_index:
  562. return i
  563. before_index = after_index
  564. package_names = []
  565. def extractPackageCode(tokens,word_index,size=20,pattern = package_code_pattern):
  566. '''
  567. @summary:抽取包附近的标段号
  568. @param:
  569. tokens:包所在句子的分词
  570. word_index:包所在字偏移
  571. size:左右各取多少个词
  572. pattern:提取标段号的正则
  573. @return: type:string,meaning:标段号
  574. '''
  575. index = changeIndexFromWordToWords(tokens,word_index)
  576. if index<size:
  577. begin = index
  578. else:
  579. begin = index-size
  580. if index+size>len(tokens):
  581. end = len(tokens)
  582. else:
  583. end = index+size
  584. #拿到左右两边的词语组成短语
  585. text = "".join(tokens[begin:end])
  586. #在短语中的字偏移
  587. new_word_index = word_index-len("".join(tokens[:begin]))
  588. min_distance = len(text)
  589. packageCode = None
  590. for the_iter in re.finditer(pattern,text):
  591. #算出最小距离
  592. distance = min([abs(new_word_index-the_iter.span()[0]),abs(new_word_index-the_iter.span()[1])])
  593. if distance<min_distance:
  594. min_distance = distance
  595. packageCode = the_iter.group(1)
  596. return packageCode
  597. #从标段介绍表格中提取包名和包号
  598. for i in range(len(list_sentence)):
  599. content = list_sentence[i].sentence_text
  600. names = re.findall(package_name_pattern,content)
  601. if names == []:
  602. names = re.findall(other_package_pattern, content)
  603. N_names = re.findall(package_N_name_pattern,content)
  604. if len(names)==1 and len(N_names)==1:
  605. package_names.append([names[0][-1],N_names[0][-1]])
  606. for i in range(len(list_sentence)):
  607. PackageList_item = []
  608. PackageList_item_scope = []
  609. content = list_sentence[i].sentence_text
  610. tokens = list_sentence[i].tokens
  611. _names = []
  612. # 2021/6/23 包名称去重
  613. for name in package_names:
  614. if name not in _names:
  615. _names.append(name)
  616. # for name in package_names[:20]:
  617. for name in _names[:20]:
  618. for index in findAllIndex(name[0],content):
  619. temp_package_number = re.findall(number_pattern,name[1])[0]
  620. if re.search(re_digital,temp_package_number):
  621. temp_package_number = str(int(temp_package_number))
  622. PackageList_item.append({"name":temp_package_number,"sentence_index":list_sentence[i].sentence_index,"offsetWords_begin":changeIndexFromWordToWords(tokens,index),"offsetWord_begin":index,"offsetWord_end":index+len(name[0])})
  623. # PackageList_item.append([temp_package_number,i,changeIndexFromWordToWords(tokens,index),index,index+len(str(temp_package_number))])
  624. code = extractPackageCode(tokens, index)
  625. if code is not None:
  626. dict_packageCode[temp_package_number] = code
  627. PackageSet.add(temp_package_number)
  628. for iter in re.finditer(package_number_pattern,content):
  629. if re.match('\d', iter.group(0)) and iter.end()<len(content) and content[iter.end()].isdigit(): # 排除2.10标段3 这种情况
  630. continue
  631. temp_package_number = re.findall(number_pattern,content[iter.span()[0]:iter.span()[1]])[0]
  632. if re.search(re_digital, temp_package_number):
  633. temp_package_number = str(int(temp_package_number))
  634. PackageList_item.append({"name":temp_package_number,"sentence_index":list_sentence[i].sentence_index,"offsetWords_begin":changeIndexFromWordToWords(tokens,iter.span()[0]),"offsetWord_begin":iter.span()[0],"offsetWord_end":iter.span()[1]})
  635. # PackageList_item.append([temp_package_number,i,changeIndexFromWordToWords(tokens,iter.span()[0]),iter.span()[0],iter.span()[1]])
  636. code = extractPackageCode(tokens, iter.span()[0])
  637. if code is not None:
  638. dict_packageCode[temp_package_number] = code
  639. PackageSet.add(temp_package_number)
  640. #识别packageScope
  641. for iter in re.finditer(pattern_packageScope,content):
  642. PackageList_item_scope.append({"name":"","sentence_index":list_sentence[i].sentence_index,"offsetWords_begin":changeIndexFromWordToWords(tokens,iter.span()[0]),"offsetWord_begin":iter.span()[0],"offsetWord_end":iter.span()[1]})
  643. # PackageList_item_scope.append(["",i,changeIndexFromWordToWords(tokens,iter.span()[0]),iter.span()[0],iter.span()[1]])
  644. PackageList_item_scope = PackageList_item +PackageList_item_scope
  645. PackageList_item_scope.sort(key=lambda x:x["offsetWord_begin"])
  646. PackageList_scope = PackageList_scope+PackageList_item_scope
  647. PackageList_item.sort(key=lambda x:x["sentence_index"])
  648. #PackageList = PackageList+PackageList_item
  649. #不作为包
  650. # if len(PackageSet)==0:
  651. # for i in range(len(list_sentence)):
  652. # PackageList_item = []
  653. # PackageList_item_scope = []
  654. # content = list_sentence[i].sentence_text
  655. # tokens = list_sentence[i].tokens
  656. # for iter in re.finditer(other_package_pattern,content):
  657. # temp_package_number = iter.group(2)
  658. # PackageList_item.append({"name":temp_package_number,"sentence_index":list_sentence[i].sentence_index,"offsetWords_begin":changeIndexFromWordToWords(tokens,iter.span()[0]),"offsetWord_begin":iter.span()[0],"offsetWord_end":iter.span()[1]})
  659. # # PackageList_item.append([temp_package_number,i,changeIndexFromWordToWords(tokens,iter.span()[0]),iter.span()[0],iter.span()[1]])
  660. # code = extractPackageCode(tokens, iter.span()[0])
  661. # if code is not None:
  662. # dict_packageCode[temp_package_number] = code
  663. # PackageSet.add(temp_package_number)
  664. # #识别packageScope
  665. # for iter in re.finditer(pattern_packageScope,content):
  666. # PackageList_item_scope.append({"name":"","sentence_index":list_sentence[i].sentence_index,"offsetWords_begin":changeIndexFromWordToWords(tokens,iter.span()[0]),"offsetWord_begin":iter.span()[0],"offsetWord_end":iter.span()[1]})
  667. # # PackageList_item_scope.append(["",i,changeIndexFromWordToWords(tokens,iter.span()[0]),iter.span()[0],iter.span()[1]])
  668. # PackageList_item_scope = PackageList_item +PackageList_item_scope
  669. # PackageList_item_scope.sort(key=lambda x:x["offsetWord_begin"])
  670. # PackageList_scope = PackageList_scope+PackageList_item_scope
  671. # PackageList_item.sort(key=lambda x:x["sentence_index"])
  672. # 2020/11/23 大网站规则 调整
  673. if len(PackageSet)==0 and len(set([it.entity_text for it in list_entity if it.entity_type in ['org', 'company'] and it.label==2]))>1:
  674. for i in range(len(list_sentence)):
  675. PackageList_item = []
  676. PackageList_item_scope = []
  677. content = list_sentence[i].sentence_text
  678. tokens = list_sentence[i].tokens
  679. names = re.findall(other_package_pattern, content)
  680. N_names = re.findall(win_tenderer_pattern, content)
  681. if len(names) != 1 or len(N_names) != 1:
  682. continue
  683. for iter in re.finditer(other_package_pattern,content):
  684. temp_package_number = iter.group(4)
  685. xinghao = re.search(model_pattern, content)
  686. if xinghao:
  687. temp_package_number = temp_package_number + '+' + xinghao.group(2)
  688. # print('新正则采购包名补充',temp_package_number)
  689. if re.search(re_digital,temp_package_number):
  690. temp_package_number = str(int(temp_package_number))
  691. PackageList_item.append({"name":temp_package_number,"sentence_index":list_sentence[i].sentence_index,"offsetWords_begin":changeIndexFromWordToWords(tokens,iter.span()[0]),"offsetWord_begin":iter.span()[0],"offsetWord_end":iter.span()[1]})
  692. # PackageList_item.append([temp_package_number,i,changeIndexFromWordToWords(tokens,iter.span()[0]),iter.span()[0],iter.span()[1]])
  693. code = extractPackageCode(tokens, iter.span()[0])
  694. if code is not None:
  695. dict_packageCode[temp_package_number] = code
  696. PackageSet.add(temp_package_number)
  697. #识别packageScope
  698. for iter in re.finditer(pattern_packageScope,content):
  699. PackageList_item_scope.append({"name":"","sentence_index":list_sentence[i].sentence_index,"offsetWords_begin":changeIndexFromWordToWords(tokens,iter.span()[0]),"offsetWord_begin":iter.span()[0],"offsetWord_end":iter.span()[1]})
  700. # PackageList_item_scope.append(["",i,changeIndexFromWordToWords(tokens,iter.span()[0]),iter.span()[0],iter.span()[1]])
  701. PackageList_item_scope = PackageList_item +PackageList_item_scope
  702. PackageList_item_scope.sort(key=lambda x:x["offsetWord_begin"])
  703. PackageList_scope = PackageList_scope+PackageList_item_scope
  704. PackageList_item.sort(key=lambda x:x["sentence_index"])
  705. pattern_punctuation = "[::()\(\),,。;;]"
  706. # print("===packageList_scope",PackageList_scope)
  707. for i in range(len(list_sentence)):
  708. for j in range(len(PackageList_scope)):
  709. if i==PackageList_scope[j]["sentence_index"] and PackageList_scope[j]["name"]!="":
  710. _flag = False
  711. left_str = list_sentence[i].sentence_text[PackageList_scope[j]["offsetWord_begin"]-30:PackageList_scope[j]["offsetWord_begin"]+1]
  712. right_str = list_sentence[i].sentence_text[PackageList_scope[j]["offsetWord_begin"]:PackageList_scope[j]["offsetWord_begin"]+30]
  713. _left_find = re.findall(pattern_punctuation,left_str)
  714. _right_find = re.findall(pattern_punctuation,right_str)
  715. #print(left_str)
  716. if re.search("同",left_str[-1:]) is not None and PackageList_scope[j]["name"]=="一":
  717. continue
  718. if re.search("划分",right_str[:10]) is not None:
  719. continue
  720. if len(_left_find)>0 and _left_find[-1] in [":",":"]:
  721. _flag = True
  722. if len(_right_find)>0 and _right_find[0] in [":",":"]:
  723. _flag = True
  724. if _flag:
  725. scope_begin = [PackageList_scope[j]["sentence_index"],PackageList_scope[j]["offsetWords_begin"]]
  726. else:
  727. if j==0:
  728. scope_begin = [0,0]
  729. else:
  730. scope_begin = [PackageList_scope[j-1]["sentence_index"],PackageList_scope[j-1]["offsetWords_begin"]]
  731. if j==len(PackageList_scope)-1:
  732. scope_end = [list_sentence[-1].sentence_index,changeIndexFromWordToWords(list_sentence[-1].tokens, len(list_sentence[-1].sentence_text))]
  733. else:
  734. scope_end = [PackageList_scope[j+1]["sentence_index"],PackageList_scope[j+1]["offsetWords_begin"]]
  735. if PackageList_scope[j-1]["sentence_index"]==PackageList_scope[j]["sentence_index"] and PackageList_scope[j-1]["offsetWord_begin"]<=PackageList_scope[j]["offsetWord_begin"] and PackageList_scope[j-1]["offsetWord_end"]>=PackageList_scope[j]["offsetWord_end"]:
  736. continue
  737. #add package to entity
  738. _pack_entity = Entity(doc_id=list_sentence[0].doc_id,entity_id="%s_%s_%s_%s"%(list_sentence[0].doc_id,i,PackageList_scope[j]["offsetWord_begin"],PackageList_scope[j]["offsetWord_begin"]),entity_text=PackageList_scope[j]["name"],entity_type="package",sentence_index=PackageList_scope[j]["sentence_index"],begin_index=changeIndexFromWordToWords(list_sentence[i].tokens,PackageList_scope[j]["offsetWord_begin"]),end_index=changeIndexFromWordToWords(list_sentence[i].tokens,PackageList_scope[j]["offsetWord_end"]),wordOffset_begin=PackageList_scope[j]["offsetWord_begin"],wordOffset_end=PackageList_scope[j]["offsetWord_end"],in_attachment=list_sentence[i].in_attachment)
  739. list_entity.append(_pack_entity)
  740. copy_pack = copy.copy(PackageList_scope[j])
  741. copy_pack["scope"] = [scope_begin,scope_end]
  742. copy_pack["hit"] = set()
  743. copy_pack["pointer"] = _pack_entity
  744. PackageList.append(copy_pack)
  745. return PackageList,PackageSet,dict_packageCode
  746. def getPackagesFromArticle(list_sentence, list_entity):
  747. '''
  748. @param:
  749. list_sentence:文章的句子list
  750. @summary: 将包的信息插入list_entity中
  751. @return: type:list if [包号,句子index,词偏移,标段号] meaning:文章的包/标段信息
  752. '''
  753. if len(list_sentence) == 0:
  754. return None
  755. list_sentence.sort(key=lambda x: x.sentence_index)
  756. PackageList = []
  757. PackageList_scope = []
  758. PackageSet = set()
  759. dict_packageCode = dict()
  760. package_number_pattern = re.compile(
  761. '((施工|监理|监测|勘察|设计|劳务)(标段)?[0-9一二三四五六七八九十ⅠⅡⅢⅣⅤⅥⅦa-zA-Z]{,4}(标段?|包))|(([a-zA-Z]包[:)]?)?第?[0-9一二三四五六七八九十ⅠⅡⅢⅣⅤⅥⅦa-zA-Z]{1,4}标段?)|((标[段号的包项]|([标分子]|合同|项目|采购|()包|包[组件号])[0-9一二三四五六七八九十ⅠⅡⅢⅣⅤⅥⅦA-Za-z]{1,4})|(([,;。、:(]|第)[0-9一二三四五六七八九十ⅠⅡⅢⅣⅤⅥⅦ]{1,4}分?包)|([a-zA-Z][0-9]{,3}分?[包标])|.{,1}((包组|包件|包号|分?包|标[段号的包]|子项目)编?号?[::]?[a-zA-Z0-9一二三四五六七八九十ⅠⅡⅢⅣⅤⅥⅦ-]+)|[,;。、:(]包[0-9一二三四五六七八九十ⅠⅡⅢⅣⅤⅥⅦ]{1,4}[^\w]') # 标号
  762. other_package_pattern = re.compile(
  763. '((项目|物资|设备|场次|标段|标的|产品)(名称)?)[::]([^,。]{2,50}?)[,。]') # # 2020/11/23 大网站规则 调整 package_N_name_pattern, package_N_name_pattern 中的项目 改为 子项目
  764. win_tenderer_pattern = re.compile('(中标候?选?人|供应商)(名称)?[::](.{2,25})[,。]') # 2020/11/23 大网站规则 调整
  765. model_pattern = re.compile('(型号|序号)[::]([^,。]{2,20})[,。]') # 2020/11/23 大网站规则 调整
  766. number_pattern = re.compile("[0-9A-Za-z一二三四五六七八九十ⅠⅡⅢⅣⅤⅥⅦ]{1,4}")
  767. package_code_pattern = re.compile("(?:编号[::]?\s*)([-\dA-Za-z\(\)]+)")
  768. # 纯数字类型的包号统一,例如:'01','1'
  769. re_digital = re.compile("^\d+$")
  770. def changeIndexFromWordToWords(tokens, word_index):
  771. '''
  772. @summary:转换某个字的字偏移为词偏移
  773. '''
  774. before_index = 0
  775. after_index = 0
  776. for i in range(len(tokens)):
  777. after_index = after_index + len(tokens[i])
  778. if before_index <= word_index and after_index >= word_index:
  779. return i
  780. before_index = after_index
  781. package_names = []
  782. def extractPackageCode(tokens, word_index, size=20, pattern=package_code_pattern):
  783. '''
  784. @summary:抽取包附近的标段号
  785. @param:
  786. tokens:包所在句子的分词
  787. word_index:包所在字偏移
  788. size:左右各取多少个词
  789. pattern:提取标段号的正则
  790. @return: type:string,meaning:标段号
  791. '''
  792. index = changeIndexFromWordToWords(tokens, word_index)
  793. if index < size:
  794. begin = index
  795. else:
  796. begin = index - size
  797. if index + size > len(tokens):
  798. end = len(tokens)
  799. else:
  800. end = index + size
  801. # 拿到左右两边的词语组成短语
  802. text = "".join(tokens[begin:end])
  803. # 在短语中的字偏移
  804. new_word_index = word_index - len("".join(tokens[:begin]))
  805. min_distance = len(text)
  806. packageCode = None
  807. for the_iter in re.finditer(pattern, text):
  808. # 算出最小距离
  809. distance = min([abs(new_word_index - the_iter.span()[0]), abs(new_word_index - the_iter.span()[1])])
  810. if distance < min_distance:
  811. min_distance = distance
  812. packageCode = the_iter.group(1)
  813. return packageCode
  814. def get_package():
  815. PackageList_scope = []
  816. True_package = set()
  817. for i in range(len(list_sentence)):
  818. PackageList_item = []
  819. PackageList_item_scope = []
  820. content = list_sentence[i].sentence_text
  821. tokens = list_sentence[i].tokens
  822. _names = []
  823. for iter in re.finditer(package_number_pattern, content):
  824. # print('提取到标段:%s, 前后文:%s'%(iter.group(), content[iter.start()-5:iter.end()+5]))
  825. if re.match('\d', iter.group(0)) and re.search('\d.$', content[:iter.start()]): # 排除2.10标段3 5.4标段划分 这种情况
  826. # print('过滤掉错误包:', iter.group())
  827. continue
  828. if re.search('[承每书/]包|XX|xx', iter.group(0)) or re.search('[a-zA-Z0-9一二三四五六七八九十ⅠⅡⅢⅣⅤⅥⅦ-]{6,}', iter.group(0)):
  829. # print('过滤掉错误包:', iter.group())
  830. continue
  831. elif iter.end()+2 < len(content) and re.search('标准|标的物|标志|包装|划分', content[iter.start():iter.end()+2]):
  832. # print('过滤掉错误包:',iter.group())
  833. continue
  834. elif re.search('同一(标段?|包)', content[max(0, iter.start()-2):iter.end()]): # 不得参加同一标段
  835. # print('过滤掉错误包:', iter.group())
  836. continue
  837. temp_package_number = uniform_package_name(iter.group(0))
  838. True_package.add(temp_package_number)
  839. PackageList_item.append({"name": temp_package_number, "sentence_index": list_sentence[i].sentence_index,
  840. "offsetWords_begin": changeIndexFromWordToWords(tokens, iter.span()[0]),
  841. "offsetWord_begin": iter.span()[0], "offsetWord_end": iter.span()[1]})
  842. # PackageList_item.append([temp_package_number,i,changeIndexFromWordToWords(tokens,iter.span()[0]),iter.span()[0],iter.span()[1]])
  843. code = extractPackageCode(tokens, iter.span()[0])
  844. if code is not None:
  845. dict_packageCode[temp_package_number] = code
  846. PackageSet.add(temp_package_number)
  847. # 识别packageScope
  848. for iter in re.finditer(pattern_packageScope, content):
  849. PackageList_item_scope.append({"name": "", "sentence_index": list_sentence[i].sentence_index,
  850. "offsetWords_begin": changeIndexFromWordToWords(tokens, iter.span()[0]),
  851. "offsetWord_begin": iter.span()[0], "offsetWord_end": iter.span()[1]})
  852. # PackageList_item_scope.append(["",i,changeIndexFromWordToWords(tokens,iter.span()[0]),iter.span()[0],iter.span()[1]])
  853. PackageList_item_scope = PackageList_item + PackageList_item_scope
  854. PackageList_item_scope.sort(key=lambda x: x["offsetWord_begin"])
  855. PackageList_scope = PackageList_scope + PackageList_item_scope
  856. PackageList_item.sort(key=lambda x: x["sentence_index"])
  857. return PackageList_scope, True_package
  858. def get_win_project():
  859. '''获取多个项目多个中标人的项目'''
  860. PackageList_scope = []
  861. True_package = set()
  862. # 2020/11/23 大网站规则 调整
  863. if len(PackageSet) == 0 and len(
  864. set([it.entity_text for it in list_entity if
  865. it.entity_type in ['org', 'company'] and it.label == 2])) > 1:
  866. for i in range(len(list_sentence)):
  867. PackageList_item = []
  868. PackageList_item_scope = []
  869. content = list_sentence[i].sentence_text
  870. tokens = list_sentence[i].tokens
  871. names = re.findall(other_package_pattern, content)
  872. N_names = re.findall(win_tenderer_pattern, content)
  873. if len(names) != 1 or len(N_names) != 1:
  874. continue
  875. for iter in re.finditer(other_package_pattern, content):
  876. temp_package_number = iter.group(4)
  877. xinghao = re.search(model_pattern, content)
  878. if xinghao:
  879. temp_package_number = temp_package_number + '+' + xinghao.group(2)
  880. # print('新正则采购包名补充',temp_package_number)
  881. if re.search(re_digital, temp_package_number):
  882. temp_package_number = str(int(temp_package_number))
  883. True_package.add(temp_package_number)
  884. PackageList_item.append(
  885. {"name": temp_package_number, "sentence_index": list_sentence[i].sentence_index,
  886. "offsetWords_begin": changeIndexFromWordToWords(tokens, iter.span()[0]),
  887. "offsetWord_begin": iter.span()[0], "offsetWord_end": iter.span()[1]})
  888. # PackageList_item.append([temp_package_number,i,changeIndexFromWordToWords(tokens,iter.span()[0]),iter.span()[0],iter.span()[1]])
  889. code = extractPackageCode(tokens, iter.span()[0])
  890. if code is not None:
  891. dict_packageCode[temp_package_number] = code
  892. PackageSet.add(temp_package_number)
  893. # 识别packageScope
  894. for iter in re.finditer(pattern_packageScope, content):
  895. PackageList_item_scope.append({"name": "", "sentence_index": list_sentence[i].sentence_index,
  896. "offsetWords_begin": changeIndexFromWordToWords(tokens,
  897. iter.span()[0]),
  898. "offsetWord_begin": iter.span()[0],
  899. "offsetWord_end": iter.span()[1]})
  900. # PackageList_item_scope.append(["",i,changeIndexFromWordToWords(tokens,iter.span()[0]),iter.span()[0],iter.span()[1]])
  901. PackageList_item_scope = PackageList_item + PackageList_item_scope
  902. PackageList_item_scope.sort(key=lambda x: x["offsetWord_begin"])
  903. PackageList_scope = PackageList_scope + PackageList_item_scope
  904. PackageList_item.sort(key=lambda x: x["sentence_index"])
  905. return PackageList_scope, True_package
  906. def get_package_scope(PackageList_scope):
  907. PackageList = []
  908. pattern_punctuation = "[::()\(\),,。;;]"
  909. # print("===packageList_scope",PackageList_scope)
  910. for i in range(len(list_sentence)):
  911. for j in range(len(PackageList_scope)):
  912. if i == PackageList_scope[j]["sentence_index"] and PackageList_scope[j]["name"] != "":
  913. _flag = False
  914. left_str = list_sentence[i].sentence_text[
  915. PackageList_scope[j]["offsetWord_begin"] - 30:PackageList_scope[j][
  916. "offsetWord_begin"] + 1]
  917. right_str = list_sentence[i].sentence_text[
  918. PackageList_scope[j]["offsetWord_begin"]:PackageList_scope[j]["offsetWord_begin"] + 30]
  919. _left_find = re.findall(pattern_punctuation, left_str)
  920. _right_find = re.findall(pattern_punctuation, right_str)
  921. # print(left_str)
  922. if re.search("同", left_str[-1:]) is not None and PackageList_scope[j]["name"] == "一":
  923. continue
  924. if re.search("划分", right_str[:10]) is not None:
  925. continue
  926. if len(_left_find) > 0 and _left_find[-1] in [":", ":"]:
  927. _flag = True
  928. if len(_right_find) > 0 and _right_find[0] in [":", ":"]:
  929. _flag = True
  930. if _flag:
  931. scope_begin = [PackageList_scope[j]["sentence_index"],
  932. PackageList_scope[j]["offsetWords_begin"]]
  933. else:
  934. if j == 0:
  935. scope_begin = [0, 0]
  936. else:
  937. scope_begin = [PackageList_scope[j - 1]["sentence_index"],
  938. PackageList_scope[j - 1]["offsetWords_begin"]]
  939. if j == len(PackageList_scope) - 1:
  940. scope_end = [list_sentence[-1].sentence_index,
  941. changeIndexFromWordToWords(list_sentence[-1].tokens,
  942. len(list_sentence[
  943. -1].sentence_text))]
  944. else:
  945. scope_end = [PackageList_scope[j + 1]["sentence_index"],
  946. PackageList_scope[j + 1]["offsetWords_begin"]]
  947. if PackageList_scope[j - 1]["sentence_index"] == PackageList_scope[j]["sentence_index"] and \
  948. PackageList_scope[j - 1]["offsetWord_begin"] <= PackageList_scope[j]["offsetWord_begin"] and \
  949. PackageList_scope[j - 1]["offsetWord_end"] >= PackageList_scope[j]["offsetWord_end"]:
  950. continue
  951. # add package to entity
  952. _pack_entity = Entity(doc_id=list_sentence[0].doc_id, entity_id="%s_%s_%s_%s" % (
  953. list_sentence[0].doc_id, i, PackageList_scope[j]["offsetWord_begin"],
  954. PackageList_scope[j]["offsetWord_begin"]), entity_text=PackageList_scope[j]["name"],
  955. entity_type="package", sentence_index=PackageList_scope[j]["sentence_index"],
  956. begin_index=changeIndexFromWordToWords(list_sentence[i].tokens,
  957. PackageList_scope[j][
  958. "offsetWord_begin"]),
  959. end_index=changeIndexFromWordToWords(list_sentence[i].tokens,
  960. PackageList_scope[j]["offsetWord_end"]),
  961. wordOffset_begin=PackageList_scope[j]["offsetWord_begin"],
  962. wordOffset_end=PackageList_scope[j]["offsetWord_end"],
  963. in_attachment=list_sentence[i].in_attachment)
  964. list_entity.append(_pack_entity)
  965. copy_pack = copy.copy(PackageList_scope[j])
  966. copy_pack["scope"] = [scope_begin, scope_end]
  967. copy_pack["hit"] = set()
  968. copy_pack["pointer"] = _pack_entity
  969. PackageList.append(copy_pack)
  970. return PackageList
  971. PackageList_scope, True_package = get_package()
  972. PackageList_scope2, True_package2 = get_win_project()
  973. if len(True_package2) > 2: # 同时包含多标段及多中标人的
  974. PackageList_scope = PackageList_scope + PackageList_scope2
  975. PackageList = get_package_scope(PackageList_scope)
  976. return PackageList, PackageSet, dict_packageCode
  977. # km配对方法
  978. def dispatch(match_list):
  979. main_roles = list(set([match.main_role for match in match_list]))
  980. attributes = list(set([match.attribute for match in match_list]))
  981. label = np.zeros(shape=(len(main_roles), len(attributes)))
  982. for match in match_list:
  983. main_role = match.main_role
  984. attribute = match.attribute
  985. value = match.value
  986. label[main_roles.index(main_role), attributes.index(attribute)] = value + 10000
  987. # print(label)
  988. gragh = -label
  989. # km算法
  990. row, col = linear_sum_assignment(gragh)
  991. max_dispatch = [(i, j) for i, j, value in zip(row, col, gragh[row, col]) if value]
  992. # return [Match(main_roles[row], attributes[col]) for row, col in max_dispatch]
  993. return [(main_roles[row], attributes[col]) for row, col in max_dispatch]
  994. from BiddingKG.dl.common.Utils import getUnifyMoney
  995. from BiddingKG.dl.interface.modelFactory import Model_relation_extraction
  996. relationExtraction_model = Model_relation_extraction()
  997. def findAttributeAfterEntity(PackDict,roleSet,PackageList,PackageSet,list_sentence,list_entity,list_outline,on_value = 0.5,on_value_person=0.5,sentence_len=4):
  998. '''
  999. @param:
  1000. PackDict:文章包dict
  1001. roleSet:文章所有角色的公司名称
  1002. PackageList:文章的包信息
  1003. PackageSet:文章所有包的名称
  1004. list_entity:文章所有经过模型处理的实体
  1005. on_value:金额模型的阈值
  1006. on_value_person:联系人模型的阈值
  1007. sentence_len:公司和属性间隔句子的最大长度
  1008. @return:添加了属性信息的角色list
  1009. '''
  1010. #根据roleid添加金额到rolelist中
  1011. def addMoneyByRoleid(packDict,packageName,roleid,money,money_prob):
  1012. for i in range(len(packDict[packageName]["roleList"])):
  1013. if packDict[packageName]["roleList"][i].role_name==dict_role_id.get(str(roleid)):
  1014. if money_prob>packDict[packageName]["roleList"][i].money_prob:
  1015. packDict[packageName]["roleList"][i].money = money
  1016. packDict[packageName]["roleList"][i].money_prob = money_prob
  1017. return packDict
  1018. #根据实体名称添加金额到rolelist中
  1019. def addMoneyByEntity(packDict,packageName,entity,money,money_prob):
  1020. for i in range(len(packDict[packageName]["roleList"])):
  1021. if packDict[packageName]["roleList"][i].entity_text==entity:
  1022. # if money_prob>packDict[packageName]["roleList"][i].money_prob:
  1023. # packDict[packageName]["roleList"][i].money = money
  1024. # packDict[packageName]["roleList"][i].money_prob = money_prob
  1025. if packDict[packageName]["roleList"][i].money_prob==0 : # 2021/7/20第一次更新金额
  1026. packDict[packageName]["roleList"][i].money = money.entity_text
  1027. packDict[packageName]["roleList"][i].money_prob = money_prob
  1028. packDict[packageName]["roleList"][i].money_unit = money.money_unit
  1029. elif money_prob>packDict[packageName]["roleList"][i].money_prob+0.2 or (money.notes in ['大写'] and money.in_attachment==False): # 2021/7/20改为优先选择大写金额,
  1030. # print('已连接金额概率:money_prob:',packDict[packageName]["roleList"][i].money_prob)
  1031. # print('链接金额备注 ',money.notes, money.entity_text, money.values)
  1032. packDict[packageName]["roleList"][i].money = money.entity_text
  1033. packDict[packageName]["roleList"][i].money_prob = money_prob
  1034. packDict[packageName]["roleList"][i].money_unit = money.money_unit
  1035. # print('链接中的金额:{0}, 单位:{1}'.format(money.entity_text, money.money_unit))
  1036. return packDict
  1037. def addRatioByEntity(packDict,packageName,entity,ratio):
  1038. for i in range(len(packDict[packageName]["roleList"])):
  1039. if packDict[packageName]["roleList"][i].entity_text==entity:
  1040. packDict[packageName]["roleList"][i].ratio = ratio.ratio_value
  1041. def addServiceTimeByEntity(packDict,packageName,entity,serviceTime):
  1042. for i in range(len(packDict[packageName]["roleList"])):
  1043. if packDict[packageName]["roleList"][i].entity_text==entity:
  1044. packDict[packageName]["roleList"][i].serviceTime = serviceTime.entity_text
  1045. #根据实体名称得到角色
  1046. def getRoleWithText(packDict,entity_text):
  1047. for pack in packDict.keys():
  1048. for i in range(len(packDict[pack]["roleList"])):
  1049. if packDict[pack]["roleList"][i].entity_text==entity_text:
  1050. return packDict[pack]["roleList"][i].role_name
  1051. def doesEntityOrLinkedEntity_inRoleSet(entity,RoleSet):
  1052. _list_entitys = [entity]+entity.linked_entitys
  1053. for _entity in _list_entitys:
  1054. if _entity.entity_text in RoleSet:
  1055. return True
  1056. p_entity = 0
  1057. # 2021/7/19 顺序比较金额,前面是后面的一万倍则把前面金额/10000
  1058. # money_list = [it for it in list_entity if it.entity_type=="money"]
  1059. # for i in range(len(money_list)-1):
  1060. # for j in range(1, len(money_list)):
  1061. # if (float(money_list[i].entity_text) > 5000000000 or money_list[j].notes=='大写') and \
  1062. # Decimal(money_list[i].entity_text)/Decimal(money_list[j].entity_text)==10000:
  1063. # money_list[i].entity_text = str(Decimal(money_list[i].entity_text)/10000)
  1064. # # print('连接前修改大于50亿金额:前面是后面的一万倍则把前面金额/10000')
  1065. '''同样金额同时有元及万元单位的,把万元的金额改为元'''
  1066. wanyuan = []
  1067. yuan = []
  1068. for it in list_entity:
  1069. if it.entity_type == "money" and float(it.entity_text)>5000:
  1070. if it.money_unit == '万元':
  1071. wanyuan.append(it)
  1072. else:
  1073. yuan.append(it)
  1074. if wanyuan != [] and yuan != []:
  1075. for m1 in wanyuan:
  1076. for m2 in yuan:
  1077. if Decimal(m1.entity_text)/Decimal(m2.entity_text) == 10000:
  1078. m1.entity_text = m2.entity_text
  1079. #遍历所有实体
  1080. # while(p_entity<len(list_entity)):
  1081. # entity = list_entity[p_entity]
  1082. '''
  1083. #招标金额从后往前找
  1084. if entity.entity_type=="money":
  1085. if entity.values[entity.label]>=on_value:
  1086. if str(entity.label)=="0":
  1087. packagePointer,_ = getPackage(PackageList,entity.sentence_index,entity.begin_index,"money-"+str(entity.label))
  1088. if packagePointer is None:
  1089. packageName = "Project"
  1090. else:
  1091. packageName = packagePointer.entity_text
  1092. addMoneyByRoleid(PackDict, packageName, "0", entity.entity_text, entity.values[entity.label])
  1093. '''
  1094. ''' # 2020/11/25 与下面的联系人连接步骤重复,取消
  1095. if entity.entity_type=="person":
  1096. if entity.values[entity.label]>=on_value_person:
  1097. if str(entity.label)=="1":
  1098. for i in range(len(PackDict["Project"]["roleList"])):
  1099. if PackDict["Project"]["roleList"][i].role_name=="tenderee":
  1100. PackDict["Project"]["roleList"][i].linklist.append((entity.entity_text,entity.person_phone))
  1101. # add pointer_person
  1102. for _entity in list_entity:
  1103. if dict_role_id.get(str(_entity.label))=="tenderee":
  1104. for i in range(len(PackDict["Project"]["roleList"])):
  1105. if PackDict["Project"]["roleList"][i].entity_text==_entity.entity_text and PackDict["Project"]["roleList"][i].role_name=="tenderee":
  1106. _entity.pointer_person = entity
  1107. elif str(entity.label)=="2":
  1108. for i in range(len(PackDict["Project"]["roleList"])):
  1109. if PackDict["Project"]["roleList"][i].role_name=="agency":
  1110. PackDict["Project"]["roleList"][i].linklist.append((entity.entity_text,entity.person_phone))
  1111. # add pointer_person
  1112. for _entity in list_entity:
  1113. if dict_role_id.get(str(_entity.label))=="agency":
  1114. for i in range(len(PackDict["Project"]["roleList"])):
  1115. if PackDict["Project"]["roleList"][i].entity_text==_entity.entity_text and PackDict["Project"]["roleList"][i].role_name=="agency":
  1116. _entity.pointer_person = entity
  1117. '''
  1118. # #金额往前找实体
  1119. # if entity.entity_type=="money":
  1120. # if entity.values[entity.label]>=on_value:
  1121. # p_entity_money= p_entity
  1122. # entity_money = list_entity[p_entity_money]
  1123. # if len(PackageSet)>0:
  1124. # packagePointer,_ = getPackage(PackageList,entity_money.sentence_index,entity_money.begin_index,"money-"+str(entity_money.entity_text)+"-"+str(entity_money.label))
  1125. # if packagePointer is None:
  1126. # packageName_entity = "Project"
  1127. # else:
  1128. # packageName_entity = packagePointer.entity_text
  1129. # else:
  1130. # packageName_entity = "Project"
  1131. # while(p_entity_money>0):
  1132. # entity_before = list_entity[p_entity_money]
  1133. # if entity_before.entity_type in ['org','company']:
  1134. # if str(entity_before.label)=="1":
  1135. # addMoneyByEntity(PackDict, packageName_entity, entity_before.entity_text, entity_money.entity_text, entity_money.values[entity_money.label])
  1136. # #add pointer_money
  1137. # entity_before.pointer_money = entity_money
  1138. # break
  1139. # p_entity_money -= 1
  1140. #如果实体属于角色集合,则往后找属性
  1141. # if doesEntityOrLinkedEntity_inRoleSet(entity, roleSet):
  1142. #
  1143. # p_entity += 1
  1144. # #循环查找符合的属性
  1145. # while(p_entity<len(list_entity)):
  1146. #
  1147. # entity_after = list_entity[p_entity]
  1148. # if entity_after.sentence_index-entity.sentence_index>=sentence_len:
  1149. # p_entity -= 1
  1150. # break
  1151. # #若是遇到公司实体,则跳出循环
  1152. # if entity_after.entity_type in ['org','company']:
  1153. # p_entity -= 1
  1154. # break
  1155. # if entity_after.values is not None:
  1156. # if entity_after.entity_type=="money":
  1157. # if entity_after.values[entity_after.label]>=on_value:
  1158. # '''
  1159. # #招标金额从后往前找
  1160. # if str(entity_after.label)=="0":
  1161. # packagePointer,_ = getPackage(PackageList,entity.sentence_index,entity.begin_index,"money-"+str(entity.label))
  1162. # if packagePointer is None:
  1163. # packageName = "Project"
  1164. # else:
  1165. # packageName = packagePointer.entity_text
  1166. # addMoneyByRoleid(PackDict, packageName, "0", entity_after.entity_text, entity_after.values[entity_after.label])
  1167. # '''
  1168. # if str(entity_after.label)=="1":
  1169. # #print(entity_after.entity_text,entity.entity_text)
  1170. # _list_entitys = [entity]+entity.linked_entitys
  1171. # if len(PackageSet)>0:
  1172. # packagePointer,_ = getPackage(PackageList,entity_after.sentence_index,entity_after.begin_index,"money-"+str(entity_after.entity_text)+"-"+str(entity_after.label))
  1173. # if packagePointer is None:
  1174. # packageName_entity = "Project"
  1175. # else:
  1176. # packageName_entity = packagePointer.entity_text
  1177. # else:
  1178. # packageName_entity = "Project"
  1179. # if str(entity.label) in ["2","3","4"]:
  1180. # # addMoneyByEntity(PackDict, packageName_entity, entity.entity_text, entity_after.entity_text, entity_after.values[entity_after.label])
  1181. # if entity_after.notes == '单价' or float(entity_after.entity_text)<5000: #2021/12/17 调整小金额阈值,避免203608823.html 两次金额一次万元没提取到的情况
  1182. # addMoneyByEntity(PackDict, packageName_entity, entity.entity_text, entity_after,
  1183. # 0.5)
  1184. # entity.pointer_money = entity_after
  1185. # # print('role zhao money', entity.entity_text, '中标金额:', entity_after.entity_text)
  1186. # else:
  1187. # addMoneyByEntity(PackDict, packageName_entity, entity.entity_text, entity_after,
  1188. # entity_after.values[entity_after.label])
  1189. # entity.pointer_money = entity_after
  1190. # # print('role zhao money', entity.entity_text, '中标金额:', entity_after.entity_text)
  1191. # if entity_after.values[entity_after.label]>0.6:
  1192. # break # 2021/7/16 新增,找到中标金额,非单价即停止,不再往后找金额
  1193. # #add pointer_money
  1194. # # entity.pointer_money = entity_after
  1195. # # print('role zhao money', entity.entity_text, '中标金额:', entity_after.entity_text)
  1196. # # if entity_after.notes!='单价':
  1197. # # break # 2021/7/16 新增,找到中标金额即停止,不再往后找金额
  1198. # '''
  1199. # if entity_after.entity_type=="person":
  1200. # if entity_after.values[entity_after.label]>=on_value_person:
  1201. # if str(entity_after.label)=="1":
  1202. # for i in range(len(roleList)):
  1203. # if roleList[i].role_name=="tenderee":
  1204. # roleList[i].linklist.append((entity_after.entity_text,entity_after.person_phone))
  1205. # elif str(entity_after.label)=="2":
  1206. # for i in range(len(roleList)):
  1207. # if roleList[i].role_name=="agency":
  1208. # roleList[i].linklist.append((entity_after.entity_text,entity_after.person_phone))
  1209. # elif str(entity_after.label)=="3":
  1210. # _list_entitys = [entity]+entity.linked_entitys
  1211. # for _entity in _list_entitys:
  1212. # for i in range(len(roleList)):
  1213. # if roleList[i].entity_text==_entity.entity_text:
  1214. # if entity_after.sentence_index-_entity.sentence_index>1 and len(roleList[i].linklist)>0:
  1215. # break
  1216. # roleList[i].linklist.append((entity_after.entity_text,entity_after.person_phone))
  1217. # '''
  1218. #
  1219. # p_entity += 1
  1220. #
  1221. # p_entity += 1
  1222. # 记录每句的分词数量
  1223. tokens_num_dict = dict()
  1224. last_tokens_num = 0
  1225. for sentence in list_sentence:
  1226. _index = sentence.sentence_index
  1227. if _index == 0:
  1228. tokens_num_dict[_index] = 0
  1229. else:
  1230. tokens_num_dict[_index] = tokens_num_dict[_index - 1] + last_tokens_num
  1231. last_tokens_num = len(sentence.tokens)
  1232. attribute_type = ['money','serviceTime','ratio']# 'money'仅指“中投标金额”
  1233. for link_attribute in attribute_type:
  1234. temp_entity_list = []
  1235. if link_attribute=="money":
  1236. temp_entity_list = [ent for ent in list_entity if (ent.entity_type in ['org','company'] and ent.label in [2,3,4]) or
  1237. (ent.entity_type=='money' and ent.label==1 and ent.values[ent.label]>=0.5)]
  1238. # 删除重复的‘中投标金额’,一般为大小写两种样式
  1239. drop_tendererMoney = []
  1240. for ent_idx in range(len(temp_entity_list)-1):
  1241. entity = temp_entity_list[ent_idx]
  1242. if entity.entity_type=='money':
  1243. next_entity = temp_entity_list[ent_idx+1]
  1244. if next_entity.entity_type=='money':
  1245. if getUnifyMoney(entity.entity_text)==getUnifyMoney(next_entity.entity_text):
  1246. if (tokens_num_dict[next_entity.sentence_index] + next_entity.begin_index) - (
  1247. tokens_num_dict[entity.sentence_index] + entity.end_index) < 10:
  1248. drop_tendererMoney.append(next_entity)
  1249. for _drop in drop_tendererMoney:
  1250. temp_entity_list.remove(_drop)
  1251. elif link_attribute=="serviceTime":
  1252. temp_entity_list = [ent for ent in list_entity if (ent.entity_type in ['org','company'] and ent.label in [2,3,4]) or
  1253. ent.entity_type=='serviceTime']
  1254. elif link_attribute=="ratio":
  1255. temp_entity_list = [ent for ent in list_entity if (ent.entity_type in ['org','company'] and ent.label in [2,3,4]) or
  1256. ent.entity_type=='ratio']
  1257. temp_entity_list = sorted(temp_entity_list,key=lambda x: (x.sentence_index, x.begin_index))
  1258. temp_match_list = []
  1259. for ent_idx in range(len(temp_entity_list)):
  1260. entity = temp_entity_list[ent_idx]
  1261. if entity.entity_type in ['org','company']:
  1262. match_nums = 0
  1263. tenderer_nums = 0 #经过其他中投标人的数量
  1264. byNotTenderer_match_nums = 0 #跟在中投标人后面的属性
  1265. for after_index in range(ent_idx + 1, min(len(temp_entity_list), ent_idx + 4)):
  1266. after_entity = temp_entity_list[after_index]
  1267. if after_entity.entity_type == link_attribute:
  1268. distance = (tokens_num_dict[after_entity.sentence_index] + after_entity.begin_index) - (
  1269. tokens_num_dict[entity.sentence_index] + entity.end_index)
  1270. sentence_distance = after_entity.sentence_index - entity.sentence_index
  1271. value = (-1 / 2 * (distance ** 2)) / 10000
  1272. if link_attribute == "money":
  1273. if after_entity.notes == '单价':
  1274. value = value * 100
  1275. if sentence_distance == 0:
  1276. if distance < 100:
  1277. # value = (-1 / 2 * (distance ** 2)) / 10000
  1278. temp_match_list.append(Match(entity, after_entity, value))
  1279. match_nums += 1
  1280. if not tenderer_nums:
  1281. byNotTenderer_match_nums += 1
  1282. else:
  1283. break
  1284. else:
  1285. if distance < 60:
  1286. # value = (-1 / 2 * (distance ** 2)) / 10000
  1287. temp_match_list.append(Match(entity, after_entity, value))
  1288. match_nums += 1
  1289. if not tenderer_nums:
  1290. byNotTenderer_match_nums += 1
  1291. else:
  1292. break
  1293. else:
  1294. tenderer_nums += 1
  1295. #前向查找属性
  1296. if ent_idx!=0 and (not match_nums or not byNotTenderer_match_nums):
  1297. previous_entity = temp_entity_list[ent_idx - 1]
  1298. if previous_entity.entity_type == link_attribute:
  1299. # if previous_entity.sentence_index == entity.sentence_index:
  1300. distance = (tokens_num_dict[entity.sentence_index] + entity.begin_index) - (
  1301. tokens_num_dict[previous_entity.sentence_index] + previous_entity.end_index)
  1302. if distance < 40:
  1303. # 前向 没有 /10000
  1304. value = (-1 / 2 * (distance ** 2))
  1305. temp_match_list.append(Match(entity, previous_entity, value))
  1306. # km算法分配求解
  1307. dispatch_result = dispatch(temp_match_list)
  1308. dispatch_result = sorted(dispatch_result, key=lambda x: (x[0].sentence_index,x[0].begin_index))
  1309. for match in dispatch_result:
  1310. _entity = match[0]
  1311. _attribute = match[1]
  1312. if link_attribute=='money':
  1313. _entity.pointer_money = _attribute
  1314. packagePointer, _ = getPackage(PackageList, _attribute.sentence_index, _attribute.begin_index,
  1315. "money-" + str(_attribute.entity_text) + "-" + str(_attribute.label))
  1316. # print(_entity.entity_text,_attribute.entity_text)
  1317. if packagePointer is None:
  1318. packageName_entity = "Project"
  1319. else:
  1320. packageName_entity = packagePointer.entity_text
  1321. if _attribute.notes == '单价' or float(_attribute.entity_text) < 5000: # 2021/12/17 调整小金额阈值,避免203608823.html 两次金额一次万元没提取到的情况
  1322. # print(packageName_entity,_attribute.entity_text, _attribute.values[_attribute.label])
  1323. addMoneyByEntity(PackDict, packageName_entity, _entity.entity_text, _attribute,0.5)
  1324. else:
  1325. # print(packageName_entity,_attribute.entity_text, _attribute.values[_attribute.label])
  1326. addMoneyByEntity(PackDict, packageName_entity, _entity.entity_text, _attribute,
  1327. _attribute.values[_attribute.label])
  1328. elif link_attribute=='serviceTime':
  1329. _entity.pointer_serviceTime = _attribute
  1330. packagePointer, _ = getPackage(PackageList, _attribute.sentence_index, _attribute.begin_index,
  1331. "serviceTime-" + str(_attribute.entity_text) + "-" + str(_attribute.label))
  1332. if packagePointer is None:
  1333. packageName_entity = "Project"
  1334. else:
  1335. packageName_entity = packagePointer.entity_text
  1336. addServiceTimeByEntity(PackDict, packageName_entity, _entity.entity_text, _attribute)
  1337. elif link_attribute=='ratio':
  1338. _entity.pointer_ratio = _attribute
  1339. packagePointer, _ = getPackage(PackageList, _attribute.sentence_index, _attribute.begin_index,
  1340. "ratio-" + str(_attribute.entity_text) + "-" + str(_attribute.label))
  1341. if packagePointer is None:
  1342. packageName_entity = "Project"
  1343. else:
  1344. packageName_entity = packagePointer.entity_text
  1345. addRatioByEntity(PackDict, packageName_entity, _entity.entity_text, _attribute)
  1346. ''''''
  1347. # 通过模型分类的招标/代理联系人
  1348. list_sentence = sorted(list_sentence, key=lambda x: x.sentence_index)
  1349. person_list = [entity for entity in list_entity if entity.entity_type == 'person' and entity.label in [1, 2]]
  1350. tenderee_contact = set()
  1351. tenderee_phone = set()
  1352. agency_contact = set()
  1353. agency_phone = set()
  1354. winter_contact = set()
  1355. for _person in person_list:
  1356. if _person.label == 1:
  1357. tenderee_contact.add(_person.entity_text)
  1358. if _person.label == 2:
  1359. agency_contact.add(_person.entity_text)
  1360. # 正则匹配无 '主体/联系人' 的电话
  1361. # 例:"采购人联系方式:0833-5226788,"
  1362. phone_pattern = '(1[3-9][0-9][-—-―]?\d{4}[-—-―]?\d{4}|' \
  1363. '\+86.?1[3-9]\d{9}|' \
  1364. '0[1-9]\d{1,2}[-—-―][1-9]\d{6,7}/[1-9]\d{6,10}|' \
  1365. '0[1-9]\d{1,2}[-—-―]\d{7,8}.?转\d{1,4}|' \
  1366. '0[1-9]\d{1,2}[-—-―]\d{7,8}[-—-―]\d{1,4}|' \
  1367. '0[1-9]\d{1,2}[-—-―]?[1-9]\d{6}\d?(?=1[3-9]\d{9})|' \
  1368. '0[1-9]\d{1,2}[-—-―]?[1-9]\d{6}\d?(?=0[1-9]\d{1,2}[-—-―]?[1-9]\d{6}\d?)|' \
  1369. '0[1-9]\d{1,2}[-—-―]?[1-9]\d{6}\d?(?=[1-9]\d{6,7})|' \
  1370. '0[1-9]\d{1,2}[-—-―]?[1-9]\d{6}\d?|' \
  1371. '[\(|\(]0[1-9]\d{1,2}[\)|\)]-?\d{7,8}-?\d{,4}|' \
  1372. '[2-9]\d{6,7})'
  1373. re_tenderee_phone = re.compile(
  1374. "(?:(?:(?:采购|招标|议价|议标|比选)(?:人|公司|单位|组织|部门)|建设(?:单位|业主)|(?:采购|招标|甲)方|询价单位|项目业主|业主)[^。]{0,5}(?:电话|联系方式|联系人|联系电话)[::]?[^。]{0,7}?)"
  1375. # 电话号码
  1376. + phone_pattern)
  1377. # 例:"采购人地址和联系方式:峨边彝族自治县教育局,0833-5226788,"
  1378. re_tenderee_phone2 = re.compile(
  1379. "(?:(?:(?:采购|招标|议价|议标|比选)(?:人|公司|单位|组织|部门)|建设(?:单位|业主)|(?:采购|招标|甲)方|询价单位|项目业主|业主)[^。]{0,3}(?:地址)[^。]{0,3}(?:电话|联系方式|联系人|联系电话)[::]?[^。]{0,20}?)"
  1380. # 电话号码
  1381. + phone_pattern)
  1382. re_agent_phone = re.compile(
  1383. "(?:(?:代理(?:人|机构|公司|单位|组织|方)|采购机构|集中采购机构|集采机构|招标机构)[^。]{0,5}(?:电话|联系方式|联系人|联系电话)[::]?[^。]{0,7}?)"
  1384. # 电话号码
  1385. + phone_pattern)
  1386. re_agent_phone2 = re.compile(
  1387. "(?:(?:代理(?:人|机构|公司|单位|组织|方)|采购机构|集中采购机构|集采机构|招标机构)[^。]{0,3}(?:地址)[^。]{0,3}(?:电话|联系方式|联系人|联系电话)[::]?[^。]{0,20}?)"
  1388. # 电话号码
  1389. + phone_pattern)
  1390. content = ""
  1391. for _sentence in list_sentence:
  1392. content += "".join(_sentence.tokens)
  1393. _content = copy.deepcopy(content)
  1394. while re.search("(.)(,)([^0-9])|([^0-9])(,)(.)", content):
  1395. content_words = list(content)
  1396. for i in re.finditer("(.)(,)([^0-9])", content):
  1397. content_words[i.span(2)[0]] = ""
  1398. for i in re.finditer("([^0-9])(,)(.)", content):
  1399. content_words[i.span(2)[0]] = ""
  1400. content = "".join(content_words)
  1401. content = re.sub("[::]|[\((]|[\))]", "", content)
  1402. _tenderee_phone = re.findall(re_tenderee_phone, content)
  1403. # 更新正则确定的角色属性
  1404. for i in range(len(PackDict["Project"]["roleList"])):
  1405. if PackDict["Project"]["roleList"][i].role_name == "tenderee":
  1406. _tenderee_phone = re.findall(re_tenderee_phone, content)
  1407. if _tenderee_phone:
  1408. for _phone in _tenderee_phone:
  1409. _phone = _phone.split("/") # 分割多个号码
  1410. for one_phone in _phone:
  1411. PackDict["Project"]["roleList"][i].linklist.append(("", one_phone))
  1412. tenderee_phone.add(one_phone)
  1413. _tenderee_phone2 = re.findall(re_tenderee_phone2, content)
  1414. if _tenderee_phone2:
  1415. for _phone in _tenderee_phone2:
  1416. _phone = _phone.split("/")
  1417. for one_phone in _phone:
  1418. PackDict["Project"]["roleList"][i].linklist.append(("", one_phone))
  1419. tenderee_phone.add(one_phone)
  1420. if PackDict["Project"]["roleList"][i].role_name == "agency":
  1421. _agent_phone = re.findall(re_agent_phone, content)
  1422. if _agent_phone:
  1423. for _phone in _agent_phone:
  1424. _phone = _phone.split("/")
  1425. for one_phone in _phone:
  1426. PackDict["Project"]["roleList"][i].linklist.append(("", one_phone))
  1427. agency_phone.add(one_phone)
  1428. _agent_phone2 = re.findall(re_agent_phone2, content)
  1429. if _agent_phone2:
  1430. for _phone in _agent_phone2:
  1431. _phone = _phone.split("/")
  1432. for one_phone in _phone:
  1433. PackDict["Project"]["roleList"][i].linklist.append(("", one_phone))
  1434. agency_phone.add(one_phone)
  1435. # 正则提取电话号码实体
  1436. # key_word = re.compile('((?:电话|联系方式|联系人).{0,4}?)([0-1]\d{6,11})')
  1437. phone = re.compile('1[3-9][0-9][-—-―]?\d{4}[-—-―]?\d{4}|'
  1438. '\+86.?1[3-9]\d{9}|'
  1439. # '0[^0]\d{1,2}[-—-―][1-9]\d{6,7}/[1-9]\d{6,10}|'
  1440. '0[1-9]\d{1,2}[-—-―]\d{7,8}.?转\d{1,4}|'
  1441. '0[1-9]\d{1,2}[-—-―]\d{7,8}[-—-―]\d{1,4}|'
  1442. '0[1-9]\d{1,2}[-—-―]?[1-9]\d{6}\d?(?=1[3-9]\d{9})|'
  1443. '0[1-9]\d{1,2}[-—-―]?[1-9]\d{6}\d?(?=0[1-9]\d{1,2}[-—-―]?[1-9]\d{6}\d?)|'
  1444. '0[1-9]\d{1,2}[-—-―]?[1-9]\d{6}\d?(?=[1-9]\d{6,7})|'
  1445. '0[1-9]\d{1,2}[-—-―]?[1-9]\d{6}\d?|'
  1446. '[\(|\(]0[1-9]\d{1,2}[\)|\)]-?\d{7,8}-?\d{,4}|'
  1447. '400\d{7}转\d{1,4}|'
  1448. '[2-9]\d{6,7}')
  1449. url_pattern = re.compile("http[s]?://(?:[a-zA-Z]|[0-9]|[#$\-_@.&+=\?:/]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+")
  1450. email_pattern = re.compile("[a-zA-Z0-9][a-zA-Z0-9_-]+(?:\.[a-zA-Z0-9_-]+)*@"
  1451. "[a-zA-Z0-9_-]+(?:\.[a-zA-Z0-9_-]+)*(?:\.[a-zA-Z]{2,})")
  1452. phone_entitys = []
  1453. code_entitys = [ent for ent in list_entity if ent.entity_type=='code']
  1454. for _sentence in list_sentence:
  1455. sentence_text = _sentence.sentence_text
  1456. # 过长数字串直接过滤替换
  1457. for _re in re.findall("\d{50,}",sentence_text):
  1458. sentence_text = sentence_text.replace(_re,"#"*len(_re))
  1459. in_attachment = _sentence.in_attachment
  1460. list_tokenbegin = []
  1461. begin = 0
  1462. for i in range(0, len(_sentence.tokens)):
  1463. list_tokenbegin.append(begin)
  1464. begin += len(str(_sentence.tokens[i]))
  1465. list_tokenbegin.append(begin + 1)
  1466. # 排除网址、邮箱、项目编号实体
  1467. error_list = []
  1468. for i in re.finditer(url_pattern, sentence_text):
  1469. error_list.append((i.start(), i.end()))
  1470. for i in re.finditer(email_pattern, sentence_text):
  1471. error_list.append((i.start(), i.end()))
  1472. for code_ent in [ent for ent in code_entitys if ent.sentence_index==_sentence.sentence_index]:
  1473. error_list.append((code_ent.wordOffset_begin,code_ent.wordOffset_end))
  1474. res_set = set()
  1475. for i in re.finditer(phone, sentence_text):
  1476. is_continue = False
  1477. for error_ent in error_list:
  1478. if i.start()>=error_ent[0] and i.end()<=error_ent[1]:
  1479. is_continue = True
  1480. break
  1481. if is_continue:
  1482. continue
  1483. res_set.add((i.group(), i.start(), i.end()))
  1484. res_set = sorted(list(res_set),key=lambda x:x[1])
  1485. # 限制数量,防止异常数据处理时间过长
  1486. res_set = res_set[:200]
  1487. last_phone_mask = True
  1488. error_numStr_index = []
  1489. sentence_phone_list = []
  1490. for item_idx in range(len(res_set)):
  1491. item = res_set[item_idx]
  1492. phone_left = sentence_text[max(0, item[1] - 10):item[1]]
  1493. phone_right = sentence_text[item[2]:item[2] + 10]
  1494. phone_left_num = re.search("[\da-zA-Z\-—-―]+$",phone_left)
  1495. numStr_left = item[1]
  1496. if phone_left_num:
  1497. numStr_left -= len(phone_left_num.group())
  1498. phone_right_num = re.search("^[\da-zA-Z\-—-―]+",phone_right)
  1499. numStr_right = item[2]
  1500. if phone_right_num:
  1501. numStr_right += len(phone_right_num.group())
  1502. numStr_index = (numStr_left,numStr_right)
  1503. if re.search("电话|手机|联系[人方]|联系方式",re.sub(",","",phone_left)):
  1504. pass
  1505. else:
  1506. # 排除“传真号”和其它错误项
  1507. if re.search("传,?真|信,?箱|邮,?[编箱件]|QQ|qq", phone_left):
  1508. if not re.search("电,?话", phone_left):
  1509. error_numStr_index.append(numStr_index)
  1510. last_phone_mask = False
  1511. continue
  1512. if re.search("身份证号?码?|注册[证号]|帐号|编[号码]|报价|标价|证号|价格|型号|附件|代码|列号|行号|税号|[\(\(]万?元[\)\)]|[a-zA-Z]+\d*$", re.sub(",","",phone_left)):
  1513. error_numStr_index.append(numStr_index)
  1514. last_phone_mask = False
  1515. continue
  1516. if re.search("^\d{0,4}[.,]\d{2,}|^[0-9a-zA-Z\.]*@|^\d*[a-zA-Z]+|元", phone_right):
  1517. error_numStr_index.append(numStr_index)
  1518. last_phone_mask = False
  1519. continue
  1520. # 号码含有0过多,不符合规则
  1521. if re.search("0{6,}",item[0]):
  1522. error_numStr_index.append(numStr_index)
  1523. last_phone_mask = False
  1524. continue
  1525. # 前后跟着字母
  1526. if re.search("[a-zA-Z/]+$", phone_left) or re.search("^[a-zA-Z/]+", phone_right):
  1527. error_numStr_index.append(numStr_index)
  1528. last_phone_mask = False
  1529. continue
  1530. # 时间日期类排除
  1531. if re.search("时间|日期", phone_left):
  1532. error_numStr_index.append(numStr_index)
  1533. last_phone_mask = False
  1534. continue
  1535. # 前后跟着长度小于一定值数字的正则排除
  1536. if re.search("\d+[-—-―]?\d*$",phone_left) or re.search("^\d+[-—-―]?\d*",phone_right):
  1537. phone_left_number = re.search("\d+[-—-―]?\d*$",phone_left)
  1538. phone_right_number = re.search("^\d+[-—-―]?\d+",phone_right)
  1539. if phone_left_number:
  1540. if len(phone_left_number.group())<7:
  1541. error_numStr_index.append(numStr_index)
  1542. last_phone_mask = False
  1543. continue
  1544. if phone_right_number:
  1545. if len(phone_right_number.group())<7:
  1546. error_numStr_index.append(numStr_index)
  1547. last_phone_mask = False
  1548. continue
  1549. left_context = re.search("[\da-zA-Z\-—-―]+$",sentence_text[:item[1]])
  1550. if left_context:
  1551. if len(left_context.group()) != len("".join(re.findall(phone, left_context.group()))):
  1552. # if not re.search("(" + phone.pattern + ")$", left_context.group()):
  1553. error_numStr_index.append(numStr_index)
  1554. last_phone_mask = False
  1555. continue
  1556. right_context = re.search("^[\da-zA-Z\-—-―]+", sentence_text[item[2]:])
  1557. if right_context:
  1558. if len(right_context.group()) != len("".join(re.findall(phone, right_context.group()))):
  1559. # if not re.search("^(" + phone.pattern + ")", right_context.group()):
  1560. error_numStr_index.append(numStr_index)
  1561. last_phone_mask = False
  1562. continue
  1563. # if:上一个phone实体不符合条件
  1564. if not last_phone_mask:
  1565. item_start = item[1]
  1566. last_item_end = res_set[item_idx-1][2]
  1567. if item_start - last_item_end<=1 or re.search("^[\da-zA-Z\-—-―、]+$",sentence_text[last_item_end:item_start]):
  1568. error_numStr_index.append(numStr_index)
  1569. last_phone_mask = False
  1570. continue
  1571. sentence_phone_list.append(item)
  1572. last_phone_mask = True
  1573. if error_numStr_index:
  1574. drop_list = []
  1575. for item in sentence_phone_list:
  1576. for err_index in error_numStr_index:
  1577. if (item[1]>=err_index[0] and item[1]<=err_index[1]) or (item[2]>=err_index[0] and item[2]<=err_index[1]) or (item[1]<=err_index[0] and item[2]>=err_index[1]):
  1578. drop_list.append(item)
  1579. break
  1580. for _drop_item in drop_list:
  1581. sentence_phone_list.remove(_drop_item)
  1582. for item in sentence_phone_list:
  1583. for j in range(len(list_tokenbegin)):
  1584. if list_tokenbegin[j] == item[1]:
  1585. begin_index = j
  1586. break
  1587. elif list_tokenbegin[j] > item[1]:
  1588. begin_index = j - 1
  1589. break
  1590. for j in range(begin_index, len(list_tokenbegin)):
  1591. if list_tokenbegin[j] >= item[2]:
  1592. end_index = j - 1
  1593. break
  1594. _entity = Entity(_sentence.doc_id, None, item[0], "phone", _sentence.sentence_index, begin_index, end_index, item[1],
  1595. item[2],in_attachment=in_attachment)
  1596. phone_entitys.append(_entity)
  1597. # print('phone_set:',set([ent.entity_text for ent in phone_entitys]))
  1598. def is_company(entity,text):
  1599. # 判断"公司"实体是否为地址地点
  1600. if entity.label!=5 and entity.values[entity.label]>0.5:
  1601. return True
  1602. if ent.is_tail==True:
  1603. return False
  1604. entity_left = text[max(0,entity.wordOffset_begin-10):entity.wordOffset_begin]
  1605. entity_left = re.sub(",()\(\)","",entity_left)
  1606. entity_left = entity_left[-5:]
  1607. if re.search("地址|地点|银行[::]",entity_left):
  1608. return False
  1609. else:
  1610. return True
  1611. pre_entity = []
  1612. for ent in list_entity:
  1613. if (ent.entity_type in ['company','org','phone'] and is_company(ent,list_sentence[ent.sentence_index].sentence_text)) or (ent.entity_type=='person' and ent.label in [1,2,3]) \
  1614. or (ent.entity_type=='location' and len(ent.entity_text)>5):
  1615. pre_entity.append(ent)
  1616. text_data,pre_data = relationExtraction_model.encode(pre_entity + phone_entitys, list_sentence)
  1617. # print(pre_data)
  1618. maxlen = 512
  1619. relation_list = []
  1620. if 0<len(text_data)<=maxlen:
  1621. relation_list = relationExtraction_model.predict(text_data, pre_data)
  1622. else:
  1623. # 公告大于maxlen时,分段预测
  1624. start = 0
  1625. # print("len(pre_data)",len(pre_data))
  1626. temp_data = []
  1627. deal_data = 0
  1628. while start<len(pre_data):
  1629. _pre_data = pre_data[start:start+maxlen]
  1630. _text_data = text_data[start:start+maxlen]
  1631. if relationExtraction_model.check_data(_pre_data):
  1632. temp_data.append((_text_data,_pre_data))
  1633. else:
  1634. if temp_data:
  1635. deal_data += len(temp_data)
  1636. if deal_data>4:
  1637. break
  1638. for _text_data, _pre_data in temp_data:
  1639. relation_list.extend(relationExtraction_model.predict(_text_data,_pre_data))
  1640. temp_data = []
  1641. start = start + maxlen - 120
  1642. if temp_data:
  1643. deal_data += len(temp_data)
  1644. if deal_data <= 4:
  1645. for _text_data, _pre_data in temp_data:
  1646. relation_list.extend(relationExtraction_model.predict(_text_data, _pre_data))
  1647. # print("预测数据:",len(temp_data))
  1648. # 去重结果
  1649. relation_list = list(set(relation_list))
  1650. # print(relation_list)
  1651. right_combination = [('org','person'),('company','person'),('company','location'),('org','location'),('person','phone')]
  1652. linked_company = set()
  1653. linked_person = set()
  1654. linked_connetPerson = set()
  1655. linked_phone = set()
  1656. for predicate in ["rel_address","rel_phone","rel_person"]:
  1657. _match_list = []
  1658. _match_combo = []
  1659. for relation in relation_list:
  1660. _subject = relation[0]
  1661. _object = relation[2]
  1662. if isinstance(_subject,Entity) and isinstance(_object,Entity) and (_subject.entity_type,_object.entity_type) in right_combination:
  1663. if relation[1]==predicate:
  1664. if predicate=="rel_person":
  1665. if (_subject.label==0 and _object.entity_text in agency_contact ) or (_subject.label==1 and _object.entity_text in tenderee_contact):
  1666. continue
  1667. # 角色为中标候选人,排除"质疑|投诉|监督|受理"相关的联系人
  1668. if _subject.label in [2,3,4] and re.search("质疑|投诉|监督|受理",list_sentence[_object.sentence_index].sentence_text[max(0,_object.wordOffset_begin-10):_object.wordOffset_begin]):
  1669. continue
  1670. distance = (tokens_num_dict[_object.sentence_index] + _object.begin_index) - (
  1671. tokens_num_dict[_subject.sentence_index] + _subject.end_index)
  1672. if distance>0:
  1673. value = (-1 / 2 * (distance ** 2))/10000
  1674. else:
  1675. distance = abs(distance)
  1676. value = (-1 / 2 * (distance ** 2))
  1677. _match_list.append(Match(_subject,_object,value))
  1678. _match_combo.append((_subject,_object))
  1679. match_result = dispatch(_match_list)
  1680. error_list = []
  1681. for mat in list(set(_match_combo)-set(match_result)):
  1682. for temp in match_result:
  1683. if mat[1]==temp[1] and mat[0]!=temp[0]:
  1684. error_list.append(mat)
  1685. break
  1686. result = list(set(_match_combo)-set(error_list))
  1687. if predicate=='rel_person':
  1688. # 从后往前更新状态,已近后向链接的属性不在前向链接(解决错误链接)
  1689. result = sorted(result,key=lambda x:x[1].begin_index,reverse=True)
  1690. for combo in result:
  1691. is_continue = False
  1692. if not combo[0].pointer_person:
  1693. combo[0].pointer_person = []
  1694. if combo[1].begin_index<combo[0].begin_index:
  1695. if combo[0].pointer_person:
  1696. for temp in combo[0].pointer_person:
  1697. if temp.begin_index>combo[0].begin_index:
  1698. is_continue = True
  1699. break
  1700. if is_continue:
  1701. continue
  1702. combo[0].pointer_person.append(combo[1])
  1703. linked_company.add(combo[0])
  1704. linked_person.add(combo[1])
  1705. # print(1,combo[0].entity_text,combo[1].entity_text)
  1706. if predicate=='rel_address':
  1707. result = sorted(result,key=lambda x:x[1].begin_index,reverse=True)
  1708. for combo in result:
  1709. if combo[0].pointer_address:
  1710. continue
  1711. combo[0].pointer_address = combo[1]
  1712. # print(2,combo[0].entity_text,combo[1].entity_text)
  1713. if predicate=='rel_phone':
  1714. result = sorted(result,key=lambda x:x[1].begin_index,reverse=True)
  1715. for combo in result:
  1716. is_continue = False
  1717. if not combo[0].person_phone:
  1718. combo[0].person_phone = []
  1719. if combo[1].begin_index<combo[0].begin_index:
  1720. if combo[0].person_phone:
  1721. for temp in combo[0].person_phone:
  1722. if temp.begin_index>combo[0].begin_index:
  1723. is_continue = True
  1724. break
  1725. if is_continue: continue
  1726. combo[0].person_phone.append(combo[1])
  1727. linked_connetPerson.add(combo[0])
  1728. linked_phone.add(combo[1])
  1729. if combo[0].label in [1,2]:
  1730. if PackDict.get("Project"):
  1731. for i in range(len(PackDict["Project"]["roleList"])):
  1732. if (combo[0].label==1 and PackDict["Project"]["roleList"][i].role_name=='tenderee') \
  1733. or (combo[0].label==2 and PackDict["Project"]["roleList"][i].role_name=='agency'):
  1734. PackDict["Project"]["roleList"][i].linklist.append((combo[0].entity_text,combo[1].entity_text))
  1735. break
  1736. # print(3,combo[0].entity_text,combo[1].entity_text)
  1737. # "公司——地址" 链接规则补充
  1738. company_lacation_EntityList = [ent for ent in pre_entity if ent.entity_type in ['company', 'org', 'location']]
  1739. # company_lacation_EntityList = [ent for ent in pre_entity if (ent.entity_type in ['company', 'org'] and ent.label!=5) or ent.entity_type=="location"]
  1740. company_lacation_EntityList = sorted(company_lacation_EntityList, key=lambda x: (x.sentence_index, x.begin_index))
  1741. t_match_list = []
  1742. for ent_idx in range(len(company_lacation_EntityList)):
  1743. entity = company_lacation_EntityList[ent_idx]
  1744. if entity.entity_type in ['company', 'org'] and entity.label!=5:
  1745. match_nums = 0
  1746. company_nums = 0 # 经过其他公司的数量
  1747. location_nums = 0 # 经过电话的数量
  1748. for after_index in range(ent_idx + 1, min(len(company_lacation_EntityList), ent_idx + 5)):
  1749. after_entity = company_lacation_EntityList[after_index]
  1750. if after_entity.entity_type == "location":
  1751. distance = (tokens_num_dict[after_entity.sentence_index] + after_entity.begin_index) - (
  1752. tokens_num_dict[entity.sentence_index] + entity.end_index)
  1753. location_nums += 1
  1754. if distance > 100 or location_nums >= 3:
  1755. break
  1756. sentence_distance = after_entity.sentence_index - entity.sentence_index
  1757. value = (-1 / 2 * (distance ** 2)) / 10000
  1758. if sentence_distance == 0:
  1759. if distance < 80:
  1760. t_match_list.append(Match(entity, after_entity, value))
  1761. match_nums += 1
  1762. if company_nums:
  1763. break
  1764. else:
  1765. if distance < 50:
  1766. t_match_list.append(Match(entity, after_entity, value))
  1767. match_nums += 1
  1768. if company_nums:
  1769. break
  1770. else:
  1771. # type:company/org
  1772. company_nums += 1
  1773. if entity.label in [2, 3, 4] and after_entity.label in [0, 1]:
  1774. break
  1775. if entity.label in [0, 1] and after_entity.label in [2, 3, 4]:
  1776. break
  1777. # km算法分配求解
  1778. # for item in t_match_list:
  1779. # print("loc_rela",item.main_role.entity_text,item.attribute.entity_text)
  1780. relate_location_result = dispatch(t_match_list)
  1781. relate_location_result = sorted(relate_location_result, key=lambda x: (x[0].sentence_index, x[0].begin_index))
  1782. for match in relate_location_result:
  1783. _company = match[0]
  1784. _relation = match[1]
  1785. # print("loc_rela2", _company.entity_text, _relation.entity_text, )
  1786. if not _company.pointer_address:
  1787. _company.pointer_address = _relation
  1788. # "联系人——联系电话" 链接规则补充
  1789. person_phone_EntityList = [ent for ent in pre_entity+ phone_entitys if ent.entity_type not in ['company','org','location']]
  1790. person_phone_EntityList = sorted(person_phone_EntityList, key=lambda x: (x.sentence_index, x.begin_index))
  1791. t_match_list = []
  1792. for ent_idx in range(len(person_phone_EntityList)):
  1793. entity = person_phone_EntityList[ent_idx]
  1794. if entity.entity_type=="person":
  1795. match_nums = 0
  1796. person_nums = 0 # 经过其他中联系人的数量
  1797. byNotPerson_match_nums = 0 # 跟在联系人后面的属性
  1798. phone_nums = 0 # 经过电话的数量
  1799. for after_index in range(ent_idx + 1, min(len(person_phone_EntityList), ent_idx + 8)):
  1800. after_entity = person_phone_EntityList[after_index]
  1801. if after_entity.entity_type == "phone":
  1802. distance = (tokens_num_dict[after_entity.sentence_index] + after_entity.begin_index) - (
  1803. tokens_num_dict[entity.sentence_index] + entity.end_index)
  1804. phone_nums += 1
  1805. if distance>100 or phone_nums>=4:
  1806. break
  1807. sentence_distance = after_entity.sentence_index - entity.sentence_index
  1808. value = (-1 / 2 * (distance ** 2)) / 10000
  1809. if sentence_distance == 0:
  1810. if distance < 80:
  1811. # value = (-1 / 2 * (distance ** 2)) / 10000
  1812. t_match_list.append(Match(entity, after_entity, value))
  1813. match_nums += 1
  1814. if not person_nums:
  1815. byNotPerson_match_nums += 1
  1816. else:
  1817. break
  1818. else:
  1819. if distance < 50:
  1820. # value = (-1 / 2 * (distance ** 2)) / 10000
  1821. t_match_list.append(Match(entity, after_entity, value))
  1822. match_nums += 1
  1823. if not person_nums:
  1824. byNotPerson_match_nums += 1
  1825. else:
  1826. break
  1827. else:
  1828. person_nums += 1
  1829. # 前向查找属性
  1830. if ent_idx != 0 and (not match_nums or not byNotPerson_match_nums):
  1831. previous_entity = person_phone_EntityList[ent_idx - 1]
  1832. if previous_entity.entity_type == 'phone':
  1833. # if previous_entity.sentence_index == entity.sentence_index:
  1834. distance = (tokens_num_dict[entity.sentence_index] + entity.begin_index) - (
  1835. tokens_num_dict[previous_entity.sentence_index] + previous_entity.end_index)
  1836. if distance < 40:
  1837. # 前向 没有 /10000
  1838. value = (-1 / 2 * (distance ** 2))
  1839. t_match_list.append(Match(entity, previous_entity, value))
  1840. # km算法分配求解(person-phone)
  1841. t_match_list = [mat for mat in t_match_list if mat.main_role not in linked_connetPerson and mat.attribute not in linked_phone]
  1842. personphone_result = dispatch(t_match_list)
  1843. personphone_result = sorted(personphone_result, key=lambda x: (x[0].sentence_index, x[0].begin_index))
  1844. for match in personphone_result:
  1845. _person = match[0]
  1846. _phone = match[1]
  1847. if not _person.person_phone:
  1848. _person.person_phone = []
  1849. _person.person_phone.append(_phone)
  1850. # 多个招标人/代理人或者别称
  1851. for idx in range(1,len(pre_entity)):
  1852. _pre_entity = pre_entity[idx]
  1853. if _pre_entity in linked_company and _pre_entity.label==5:
  1854. last_ent = pre_entity[idx-1]
  1855. if last_ent.entity_type in ['company','org'] and last_ent.label in [0,1]:
  1856. if last_ent.sentence_index==_pre_entity.sentence_index:
  1857. mid_text = list_sentence[_pre_entity.sentence_index].sentence_text[last_ent.wordOffset_end:_pre_entity.wordOffset_begin]
  1858. if len(mid_text)<=20 and "," not in mid_text and re.search("[、\((]",mid_text):
  1859. _pre_entity.label = last_ent.label
  1860. _pre_entity.values[last_ent.label] = 0.6
  1861. # 2022/01/25 固定电话可连多个联系人
  1862. temp_person_entitys = [entity for entity in pre_entity if entity.entity_type == 'person']
  1863. temp_person_entitys2 = [] #和固定电话相连的联系人
  1864. for entity in temp_person_entitys:
  1865. if entity.person_phone:
  1866. for _phone in entity.person_phone:
  1867. if not re.search("^1[3-9]\d{9}$", _phone.entity_text):
  1868. temp_person_entitys2.append(entity)
  1869. break
  1870. for index in range(len(temp_person_entitys)):
  1871. entity = temp_person_entitys[index]
  1872. if entity in temp_person_entitys2:
  1873. last_person = entity
  1874. for after_index in range(index + 1, min(len(temp_person_entitys), index + 5)):
  1875. after_entity = temp_person_entitys[after_index]
  1876. if after_entity.sentence_index == last_person.sentence_index and after_entity.begin_index - last_person.end_index < 3:
  1877. for _phone in entity.person_phone:
  1878. if not re.search("^1[3-9]\d{9}$", _phone.entity_text):
  1879. if _phone not in after_entity.person_phone:
  1880. after_entity.person_phone.append(_phone)
  1881. last_person = after_entity
  1882. else:
  1883. break
  1884. if index==0:
  1885. continue
  1886. last_person = entity
  1887. for before_index in range(index-1, max(-1,index-5), -1):
  1888. before_entity = temp_person_entitys[before_index]
  1889. if before_entity.sentence_index == last_person.sentence_index and last_person.begin_index - before_entity.end_index < 3:
  1890. for _phone in entity.person_phone:
  1891. if not re.search("^1[3-9]\d{9}$", _phone.entity_text):
  1892. if _phone not in before_entity.person_phone:
  1893. before_entity.person_phone.append(_phone)
  1894. last_person = before_entity
  1895. else:
  1896. break
  1897. # 更新person为招标/代理联系人的联系方式
  1898. for k in PackDict.keys():
  1899. for i in range(len(PackDict[k]["roleList"])):
  1900. if PackDict[k]["roleList"][i].role_name == "tenderee":
  1901. for _person in person_list:
  1902. if _person.label==1:#招标联系人
  1903. person_phone = [phone for phone in _person.person_phone] if _person.person_phone else []
  1904. for _p in person_phone:
  1905. PackDict[k]["roleList"][i].linklist.append((_person.entity_text, _p.entity_text))
  1906. if not person_phone:
  1907. PackDict[k]["roleList"][i].linklist.append((_person.entity_text,""))
  1908. if PackDict[k]["roleList"][i].role_name == "agency":
  1909. for _person in person_list:
  1910. if _person.label==2:#代理联系人
  1911. person_phone = [phone for phone in _person.person_phone] if _person.person_phone else []
  1912. for _p in person_phone:
  1913. PackDict[k]["roleList"][i].linklist.append((_person.entity_text, _p.entity_text))
  1914. if not person_phone:
  1915. PackDict[k]["roleList"][i].linklist.append((_person.entity_text,""))
  1916. # 更新 PackDict
  1917. not_sure_linked = []
  1918. for link_p in list(linked_company):
  1919. for k in PackDict.keys():
  1920. for i in range(len(PackDict[k]["roleList"])):
  1921. if PackDict[k]["roleList"][i].role_name == "tenderee":
  1922. if PackDict[k]["roleList"][i].entity_text != link_p.entity_text and link_p.label == 0:
  1923. not_sure_linked.append(link_p)
  1924. continue
  1925. if PackDict[k]["roleList"][i].entity_text == link_p.entity_text:
  1926. for per in link_p.pointer_person:
  1927. person_phone = [phone for phone in per.person_phone] if per.person_phone else []
  1928. if not person_phone:
  1929. if per.entity_text not in agency_contact:
  1930. PackDict[k]["roleList"][i].linklist.append((per.entity_text, ""))
  1931. continue
  1932. for _p in person_phone:
  1933. if per.entity_text not in agency_contact and _p.entity_text not in agency_phone:
  1934. PackDict[k]["roleList"][i].linklist.append((per.entity_text, _p.entity_text))
  1935. elif PackDict[k]["roleList"][i].role_name == "agency":
  1936. if PackDict[k]["roleList"][i].entity_text != link_p.entity_text and link_p.label == 1:
  1937. not_sure_linked.append(link_p)
  1938. continue
  1939. if PackDict[k]["roleList"][i].entity_text == link_p.entity_text:
  1940. for per in link_p.pointer_person:
  1941. person_phone = [phone for phone in per.person_phone] if per.person_phone else []
  1942. if not person_phone:
  1943. if per.entity_text not in tenderee_contact:
  1944. PackDict[k]["roleList"][i].linklist.append((per.entity_text, ""))
  1945. continue
  1946. for _p in person_phone:
  1947. if per.entity_text not in tenderee_contact and _p.entity_text not in tenderee_phone:
  1948. PackDict[k]["roleList"][i].linklist.append((per.entity_text, _p.entity_text))
  1949. else:
  1950. if PackDict[k]["roleList"][i].entity_text == link_p.entity_text:
  1951. for per in link_p.pointer_person:
  1952. person_phone = [phone for phone in per.person_phone] if per.person_phone else []
  1953. if not person_phone:
  1954. if per.entity_text not in tenderee_contact and per.entity_text not in agency_contact:
  1955. PackDict[k]["roleList"][i].linklist.append((per.entity_text, ""))
  1956. winter_contact.add(per.entity_text)
  1957. continue
  1958. for _p in person_phone:
  1959. if per.entity_text not in tenderee_contact and _p.entity_text not in tenderee_phone and \
  1960. per.entity_text not in agency_contact and _p.entity_text not in agency_phone:
  1961. PackDict[k]["roleList"][i].linklist.append((per.entity_text, _p.entity_text))
  1962. winter_contact.add(per.entity_text)
  1963. # 更新org/company实体label为0,1的链接
  1964. for link_p in not_sure_linked:
  1965. for k in PackDict.keys():
  1966. for i in range(len(PackDict[k]["roleList"])):
  1967. if PackDict[k]["roleList"][i].role_name == "tenderee":
  1968. if link_p.label == 0:
  1969. for per in link_p.pointer_person:
  1970. person_phone = [phone for phone in per.person_phone] if per.person_phone else []
  1971. if not person_phone:
  1972. if per.entity_text not in agency_contact and per.entity_text not in winter_contact:
  1973. PackDict[k]["roleList"][i].linklist.append((per.entity_text, ""))
  1974. continue
  1975. for _p in person_phone:
  1976. if per.entity_text not in agency_contact and _p.entity_text not in agency_phone and per.entity_text not in winter_contact:
  1977. PackDict[k]["roleList"][i].linklist.append((per.entity_text, _p.entity_text))
  1978. elif PackDict[k]["roleList"][i].role_name == "agency":
  1979. if link_p.label == 1:
  1980. for per in link_p.pointer_person:
  1981. person_phone = [phone for phone in per.person_phone] if per.person_phone else []
  1982. if not person_phone:
  1983. if per.entity_text not in tenderee_contact and per.entity_text not in winter_contact:
  1984. PackDict[k]["roleList"][i].linklist.append((per.entity_text, ""))
  1985. continue
  1986. for _p in person_phone:
  1987. if per.entity_text not in tenderee_contact and _p.entity_text not in tenderee_phone and per.entity_text not in winter_contact:
  1988. PackDict[k]["roleList"][i].linklist.append((per.entity_text, _p.entity_text))
  1989. re_split = re.compile("[^\u4e00-\u9fa5、](十一|十二|十三|十四|十五|一|二|三|四|五|六|七|八|九|十)、")
  1990. split_list = [0] * 16
  1991. split_dict = {
  1992. "一、": 1,
  1993. "二、": 2,
  1994. "三、": 3,
  1995. "四、": 4,
  1996. "五、": 5,
  1997. "六、": 6,
  1998. "七、": 7,
  1999. "八、": 8,
  2000. "九、": 9,
  2001. "十、": 10,
  2002. "十一、": 11,
  2003. "十二、": 12,
  2004. "十三、": 13,
  2005. "十四、": 14,
  2006. "十五、": 15
  2007. }
  2008. for item in re.finditer(re_split, _content):
  2009. _index = split_dict.get(item.group()[1:])
  2010. if not split_list[_index]:
  2011. split_list[_index] = item.span()[0] + 1
  2012. split_list = [i for i in split_list if i != 0]
  2013. start = 0
  2014. new_split_list = []
  2015. for idx in split_list:
  2016. new_split_list.append((start, idx))
  2017. start = idx
  2018. new_split_list.append((start, len(_content)))
  2019. # 实体列表按照“公告分段”分组
  2020. words_num_dict = dict()
  2021. last_words_num = 0
  2022. for sentence in list_sentence:
  2023. _index = sentence.sentence_index
  2024. if _index == 0:
  2025. words_num_dict[_index] = 0
  2026. else:
  2027. words_num_dict[_index] = words_num_dict[_index - 1] + last_words_num
  2028. last_words_num = len(sentence.sentence_text)
  2029. # 公司-联系人连接(km算法)
  2030. re_phone = re.compile('1[3-9][0-9][-—-―]?\d{4}[-—-―]?\d{4}|'
  2031. '\+86.?1[3-9]\d{9}|'
  2032. '0[1-9]\d{1,2}[-—-―][1-9]\d{6,7}/[1-9]\d{6,10}|'
  2033. '0[1-9]\d{1,2}[-—-―]\d{7,8}.?转\d{1,4}|'
  2034. '0[1-9]\d{1,2}[-—-―]\d{7,8}[-—-―]\d{1,4}|'
  2035. '0[1-9]\d{1,2}[-—-―]?[1-9]\d{6}\d?(?=1[3-9]\d{9})|'
  2036. '0[1-9]\d{1,2}[-—-―]?[1-9]\d{6}\d?(?=0[1-9]\d{1,2}[-—-―]?[1-9]\d{6}\d?)|'
  2037. '0[1-9]\d{1,2}[-—-―]?[1-9]\d{6}\d?(?=[1-9]\d{6,7})|'
  2038. '0[1-9]\d{1,2}[-—-―]?[1-9]\d{6}\d?|'
  2039. '[\(|\(]0[1-9]\d{1,2}[\)|\)]-?\d{7,8}-?\d{,4}|'
  2040. '[2-9]\d{6,7}')
  2041. key_phone = re.compile("联系方式|电话|联系人|负责人")
  2042. temporary_list2 = []
  2043. for entity in list_entity:
  2044. # if entity.entity_type in ['org', 'company', 'person'] and entity.is_tail==False:
  2045. if entity.entity_type in ['org', 'company', 'person']:
  2046. temporary_list2.append(entity)
  2047. temporary_list2 = sorted(temporary_list2, key=lambda x: (x.sentence_index, x.begin_index))
  2048. new_temporary_list2 = []
  2049. for _split in new_split_list:
  2050. temp_list = []
  2051. for _entity in temporary_list2:
  2052. if words_num_dict[_entity.sentence_index] + _entity.wordOffset_begin >= _split[0] and words_num_dict[
  2053. _entity.sentence_index] + _entity.wordOffset_end < _split[1]:
  2054. temp_list.append(_entity)
  2055. elif words_num_dict[_entity.sentence_index] + _entity.wordOffset_begin >= _split[1]:
  2056. break
  2057. new_temporary_list2.append(temp_list)
  2058. # print(new_temporary_list2)
  2059. match_list2 = []
  2060. for split_index in range(len(new_temporary_list2)):
  2061. split_entitys = new_temporary_list2[split_index]
  2062. is_skip = False
  2063. for index in range(len(split_entitys)):
  2064. entity = split_entitys[index]
  2065. if is_skip:
  2066. is_skip = False
  2067. continue
  2068. else:
  2069. if entity.entity_type in ['org', 'company']:
  2070. if entity.label != 5 or entity.entity_text in roleSet:
  2071. match_nums = 0
  2072. for after_index in range(index + 1, min(len(split_entitys), index + 4)):
  2073. after_entity = split_entitys[after_index]
  2074. if after_entity.entity_type in ['person']:
  2075. # 实体为中标人/候选人,联系人已确定类别【1,2】
  2076. if entity.label in [2, 3, 4] and after_entity.label in [1, 2]:
  2077. break
  2078. # 角色为中标候选人,排除"质疑|投诉|监督|受理"相关的联系人
  2079. if entity.label in [2, 3, 4] and re.search("质疑|投诉|监督|受理", list_sentence[after_entity.sentence_index].sentence_text[max(0,after_entity.wordOffset_begin - 10):after_entity.wordOffset_begin]):
  2080. break
  2081. if after_entity.label in [1, 2, 3]:
  2082. distance = (tokens_num_dict[
  2083. after_entity.sentence_index] + after_entity.begin_index) - (
  2084. tokens_num_dict[entity.sentence_index] + entity.end_index)
  2085. sentence_distance = after_entity.sentence_index - entity.sentence_index
  2086. if sentence_distance == 0:
  2087. if distance < 100:
  2088. if (entity.label == 0 and after_entity.label == 1) or (
  2089. entity.label == 1 and after_entity.label == 2):
  2090. distance = distance / 100
  2091. value = (-1 / 2 * (distance ** 2)) / 10000
  2092. match_list2.append(Match(entity, after_entity, value))
  2093. match_nums += 1
  2094. else:
  2095. if distance < 60:
  2096. if (entity.label == 0 and after_entity.label == 1) or (
  2097. entity.label == 1 and after_entity.label == 2):
  2098. distance = distance / 100
  2099. value = (-1 / 2 * (distance ** 2)) / 10000
  2100. match_list2.append(Match(entity, after_entity, value))
  2101. match_nums += 1
  2102. if after_entity.entity_type in ['org', 'company']:
  2103. if entity.label in [2, 3, 4] and after_entity.label in [0, 1]:
  2104. break
  2105. # 解决在‘地址’中识别出org/company的问题
  2106. # if entity.label in [0,1] and after_index==index+1 and after_entity.label not in [0,1]:
  2107. if entity.label != 5 and after_index == index + 1 and (
  2108. after_entity.label == entity.label or after_entity.label == 5):
  2109. distance = (tokens_num_dict[
  2110. after_entity.sentence_index] + after_entity.begin_index) - (
  2111. tokens_num_dict[entity.sentence_index] + entity.end_index)
  2112. if distance < 20:
  2113. after_entity_left = list_sentence[after_entity.sentence_index].tokens[max(0,
  2114. after_entity.begin_index - 10):after_entity.begin_index]
  2115. after_entity_right = list_sentence[after_entity.sentence_index].tokens[
  2116. after_entity.end_index + 1:after_entity.end_index + 6]
  2117. after_entity_left = "".join(after_entity_left)
  2118. if len(after_entity_left) > 20:
  2119. after_entity_left = after_entity_left[-20:]
  2120. after_entity_right = "".join(after_entity_right)[:10]
  2121. if re.search("地,?址", after_entity_left):
  2122. is_skip = True
  2123. continue
  2124. if re.search("\(|(", after_entity_left) and re.search("\)|)",
  2125. after_entity_right):
  2126. is_skip = True
  2127. continue
  2128. if entity.label in [0, 1] and after_entity.label in [0,
  2129. 1] and entity.label == after_entity.label:
  2130. break
  2131. if entity.label in [0, 1] and after_entity.label in [0, 1] and split_entitys[
  2132. index + 1].entity_type == "person":
  2133. break
  2134. if entity.label in [0, 1] and after_entity.label in [2, 3, 4]:
  2135. break
  2136. if entity.label in [2, 3, 4] and after_entity.label in [0, 1]:
  2137. break
  2138. # 搜索没有联系人的电话
  2139. mid_tokens = []
  2140. is_same_sentence = False
  2141. if index == len(split_entitys) - 1:
  2142. for i in range(entity.sentence_index, len(list_sentence)):
  2143. mid_tokens += list_sentence[i].tokens
  2144. mid_tokens = mid_tokens[entity.end_index + 1:]
  2145. mid_sentence = "".join(mid_tokens)
  2146. have_phone = re.findall(re_phone, mid_sentence)
  2147. if have_phone:
  2148. if re.findall(re_phone, mid_sentence.split("。")[0]):
  2149. is_same_sentence = True
  2150. _phone = have_phone[0]
  2151. if _phone in [ent.entity_text for ent in phone_entitys]:
  2152. phone_begin = mid_sentence.find(_phone)
  2153. if words_num_dict[entity.sentence_index] + entity.wordOffset_begin + phone_begin < \
  2154. new_split_list[split_index][1]:
  2155. mid_sentence = mid_sentence[max(0, phone_begin - 15):phone_begin].replace(",", "")
  2156. if re.search(key_phone, mid_sentence):
  2157. distance = 1
  2158. if is_same_sentence:
  2159. if phone_begin <= 200:
  2160. value = (-1 / 2 * (distance ** 2)) / 10000
  2161. match_list2.append(Match(entity, (entity, _phone), value))
  2162. match_nums += 1
  2163. else:
  2164. if phone_begin <= 60:
  2165. value = (-1 / 2 * (distance ** 2)) / 10000
  2166. match_list2.append(Match(entity, (entity, _phone), value))
  2167. match_nums += 1
  2168. else:
  2169. next_entity = split_entitys[index + 1]
  2170. if next_entity.entity_type in ["org","company"]:
  2171. _entity_left = list_sentence[next_entity.sentence_index].sentence_text[max(0, next_entity.wordOffset_begin - 20):next_entity.wordOffset_begin]
  2172. _entity_left2 = re.sub(",()\(\)::", "", _entity_left)
  2173. _entity_left2 = _entity_left2[-5:]
  2174. if re.search("(地,?址|地,?点)[::][^,。]*$", _entity_left) or re.search("地址|地点", _entity_left2):
  2175. if index + 2<= len(split_entitys) - 1:
  2176. next_entity = split_entitys[index + 2]
  2177. if entity.sentence_index == next_entity.sentence_index:
  2178. mid_tokens += list_sentence[entity.sentence_index].tokens[
  2179. entity.end_index + 1:next_entity.begin_index]
  2180. else:
  2181. sentence_index = entity.sentence_index
  2182. while sentence_index <= next_entity.sentence_index:
  2183. mid_tokens += list_sentence[sentence_index].tokens
  2184. sentence_index += 1
  2185. mid_tokens = mid_tokens[entity.end_index + 1:-(len(
  2186. list_sentence[next_entity.sentence_index].tokens) - next_entity.begin_index) + 1]
  2187. mid_sentence = "".join(mid_tokens)
  2188. have_phone = re.findall(re_phone, mid_sentence)
  2189. if have_phone:
  2190. if re.findall(re_phone, mid_sentence.split("。")[0]):
  2191. is_same_sentence = True
  2192. _phone = have_phone[0]
  2193. if _phone in [ent.entity_text for ent in phone_entitys]:
  2194. phone_begin = mid_sentence.find(_phone)
  2195. mid_sentence = mid_sentence[max(0, phone_begin - 15):phone_begin].replace(",", "")
  2196. if re.search(key_phone, mid_sentence):
  2197. p_phone = [p.entity_text for p in next_entity.person_phone] if next_entity.person_phone else []
  2198. if next_entity.entity_type == 'person' and _phone in p_phone:
  2199. pass
  2200. else:
  2201. distance = (tokens_num_dict[
  2202. next_entity.sentence_index] + next_entity.begin_index) - (
  2203. tokens_num_dict[entity.sentence_index] + entity.end_index)
  2204. distance = distance / 2
  2205. if is_same_sentence:
  2206. if phone_begin <= 200:
  2207. value = (-1 / 2 * (distance ** 2)) / 10000
  2208. match_list2.append(Match(entity, (entity, _phone), value))
  2209. match_nums += 1
  2210. else:
  2211. if phone_begin <= 60:
  2212. value = (-1 / 2 * (distance ** 2)) / 10000
  2213. match_list2.append(Match(entity, (entity, _phone), value))
  2214. match_nums += 1
  2215. # 实体无匹配时,尝试前向查找匹配
  2216. if not match_nums:
  2217. if (entity.label != 5 or entity.entity_text in roleSet) and entity.values[entity.label] >= 0.5 and index != 0:
  2218. previous_entity = split_entitys[index - 1]
  2219. if previous_entity.entity_type == 'person' and previous_entity.label in [1, 2, 3]:
  2220. if entity.label in [2, 3, 4] and previous_entity.label in [1, 2]:
  2221. continue
  2222. if previous_entity.sentence_index == entity.sentence_index:
  2223. distance = (tokens_num_dict[entity.sentence_index] + entity.begin_index) - (
  2224. tokens_num_dict[
  2225. previous_entity.sentence_index] + previous_entity.end_index)
  2226. if distance < 20:
  2227. # 距离相等时,前向添加处罚值
  2228. # distance += 1
  2229. # 前向 没有 /10000
  2230. value = (-1 / 2 * (distance ** 2))
  2231. match_list2.append(Match(entity, previous_entity, value))
  2232. # print(match_list2)
  2233. match_list2 = [mat for mat in match_list2 if mat.main_role not in linked_company and mat.attribute not in linked_person]
  2234. # print(match_list2)
  2235. # km算法分配求解
  2236. result2 = dispatch(match_list2)
  2237. # print(result2)
  2238. for match in result2:
  2239. entity = match[0]
  2240. # print(entity.entity_text)
  2241. # print(match.attribute)
  2242. entity_index = list_entity.index(entity)
  2243. is_update = False
  2244. if isinstance(match[1], tuple):
  2245. person_ = ''
  2246. phone_ = match[1][1].split("/") # 分割多个号码
  2247. # print(person_,phone_)
  2248. else:
  2249. person_ = match[1].entity_text
  2250. phone_ = [i.entity_text for i in match[1].person_phone] if match[1].person_phone else []
  2251. for k in PackDict.keys():
  2252. for i in range(len(PackDict[k]["roleList"])):
  2253. if PackDict[k]["roleList"][i].role_name == "tenderee":
  2254. # if not PackDict[k]["roleList"][i].linklist:
  2255. if PackDict[k]["roleList"][i].entity_text == entity.entity_text or entity.label == 0:
  2256. if person_ not in agency_contact and len(set(phone_)&set(agency_phone))==0 and person_ not in winter_contact:
  2257. if not phone_:
  2258. PackDict[k]["roleList"][i].linklist.append((person_, ""))
  2259. for p in phone_:
  2260. # if not person_ and len()
  2261. PackDict[k]["roleList"][i].linklist.append((person_, p))
  2262. is_update = True
  2263. elif PackDict[k]["roleList"][i].role_name == "agency":
  2264. # if not PackDict[k]["roleList"][i].linklist:
  2265. if PackDict[k]["roleList"][i].entity_text == entity.entity_text or entity.label == 1 and person_ not in winter_contact:
  2266. if person_ not in tenderee_contact and len(set(phone_)&set(tenderee_phone))==0:
  2267. if not phone_:
  2268. PackDict[k]["roleList"][i].linklist.append((person_, ""))
  2269. for p in phone_:
  2270. PackDict[k]["roleList"][i].linklist.append((person_, p))
  2271. is_update = True
  2272. else:
  2273. if PackDict[k]["roleList"][i].entity_text == entity.entity_text:
  2274. if not PackDict[k]["roleList"][i].linklist:
  2275. if person_ not in tenderee_contact and len(set(phone_)&set(tenderee_phone))==0 and \
  2276. person_ not in agency_contact and len(set(phone_)&set(agency_phone))==0:
  2277. if not phone_:
  2278. PackDict[k]["roleList"][i].linklist.append((person_, ""))
  2279. for p in phone_:
  2280. PackDict[k]["roleList"][i].linklist.append((person_, p))
  2281. is_update = True
  2282. if not person_:
  2283. is_update = False
  2284. if is_update:
  2285. # 更新 list_entity
  2286. if not list_entity[entity_index].pointer_person:
  2287. list_entity[entity_index].pointer_person = []
  2288. list_entity[entity_index].pointer_person.append(match[1])
  2289. linked_person = []
  2290. linked_persons_with = []
  2291. for company_entity in [entity for entity in list_entity if entity.entity_type in ['company','org']]:
  2292. if company_entity.pointer_person:
  2293. for _person in company_entity.pointer_person:
  2294. linked_person.append(_person)
  2295. linked_persons_with.append(company_entity)
  2296. # 一个公司对应多个联系人的补充
  2297. person_entitys = [entity for entity in list_entity if entity.entity_type=='person']
  2298. person_entitys = person_entitys[::-1]
  2299. for index in range(len(person_entitys)):
  2300. entity = person_entitys[index]
  2301. prepare_link = []
  2302. if entity not in linked_person:
  2303. prepare_link.append(entity)
  2304. last_person = entity
  2305. for after_index in range(index + 1, min(len(person_entitys), index + 5)):
  2306. after_entity = person_entitys[after_index]
  2307. if after_entity.sentence_index==last_person.sentence_index and last_person.begin_index-after_entity.end_index<5:
  2308. if after_entity in linked_person:
  2309. _index = linked_person.index(after_entity)
  2310. with_company = linked_persons_with[_index]
  2311. for i in range(len(PackDict["Project"]["roleList"])):
  2312. if PackDict["Project"]["roleList"][i].role_name == "tenderee":
  2313. if PackDict["Project"]["roleList"][i].entity_text == with_company.entity_text or with_company.label == 0:
  2314. for item in prepare_link:
  2315. person_phone = [p.entity_text for p in item.person_phone] if item.person_phone else []
  2316. for _p in person_phone:
  2317. PackDict["Project"]["roleList"][i].linklist.append((item.entity_text, _p))
  2318. with_company.pointer_person.append(item)
  2319. linked_person.append(item)
  2320. elif PackDict["Project"]["roleList"][i].role_name == "agency":
  2321. if PackDict["Project"]["roleList"][i].entity_text == with_company.entity_text or with_company.label == 1:
  2322. for item in prepare_link:
  2323. person_phone = [p.entity_text for p in item.person_phone] if item.person_phone else []
  2324. for _p in person_phone:
  2325. PackDict["Project"]["roleList"][i].linklist.append((item.entity_text, _p))
  2326. with_company.pointer_person.append(item)
  2327. linked_person.append(item)
  2328. else:
  2329. if PackDict["Project"]["roleList"][i].entity_text == with_company.entity_text:
  2330. for item in prepare_link:
  2331. person_phone = [p.entity_text for p in item.person_phone] if item.person_phone else []
  2332. for _p in person_phone:
  2333. PackDict["Project"]["roleList"][i].linklist.append((item.entity_text, _p))
  2334. with_company.pointer_person.append(item)
  2335. linked_person.append(item)
  2336. break
  2337. else:
  2338. prepare_link.append(after_entity)
  2339. last_person = after_entity
  2340. continue
  2341. # 统一同类角色的属性
  2342. for k in PackDict.keys():
  2343. for i in range(len(PackDict[k]["roleList"])):
  2344. for _entity in list_entity:
  2345. if _entity.entity_type in ['org','company']:
  2346. is_same = False
  2347. is_similar = False
  2348. # entity_text相同
  2349. if _entity.entity_text==PackDict[k]["roleList"][i].entity_text:
  2350. is_same = True
  2351. # entity.label为【0,1】
  2352. if _entity.label in [0,1] and dict_role_id[str(_entity.label)]==PackDict[k]["roleList"][i].role_name:
  2353. is_similar = True
  2354. if is_same:
  2355. linked_entitys = _entity.linked_entitys
  2356. if linked_entitys:
  2357. for linked_entity in linked_entitys:
  2358. pointer_person = linked_entity.pointer_person if linked_entity.pointer_person else []
  2359. for _pointer_person in pointer_person:
  2360. _phone = [p.entity_text for p in _pointer_person.person_phone] if _pointer_person.person_phone else []
  2361. for _p in _phone:
  2362. if (_pointer_person.entity_text,_p) not in PackDict[k]["roleList"][i].linklist:
  2363. PackDict[k]["roleList"][i].linklist.append((_pointer_person.entity_text,_p))
  2364. elif is_similar:
  2365. pointer_person = _entity.pointer_person if _entity.pointer_person else []
  2366. for _pointer_person in pointer_person:
  2367. _phone = [p.entity_text for p in _pointer_person.person_phone] if _pointer_person.person_phone else []
  2368. for _p in _phone:
  2369. if (_pointer_person.entity_text, _p) not in PackDict[k]["roleList"][i].linklist:
  2370. PackDict[k]["roleList"][i].linklist.append(
  2371. (_pointer_person.entity_text, _p))
  2372. # "roleList"中联系人电话去重
  2373. for k in PackDict.keys():
  2374. for i in range(len(PackDict[k]["roleList"])):
  2375. # 带有联系人的电话
  2376. with_person = [person_phone[1] for person_phone in PackDict[k]["roleList"][i].linklist if person_phone[0]]
  2377. # 带有电话的联系人
  2378. with_phone = [person_phone[0] for person_phone in PackDict[k]["roleList"][i].linklist if person_phone[1]]
  2379. remove_list = []
  2380. for item in PackDict[k]["roleList"][i].linklist:
  2381. if not item[0]:
  2382. if item[1] in with_person:
  2383. # 删除重复的无联系人电话
  2384. remove_list.append(item)
  2385. elif not item[1]:
  2386. if item[0] in with_phone:
  2387. remove_list.append(item)
  2388. for _item in remove_list:
  2389. PackDict[k]["roleList"][i].linklist.remove(_item)
  2390. # PackDict更新company/org地址
  2391. last_role_prob = {}
  2392. for ent in pre_entity:
  2393. if ent.entity_type in ['company','org']:
  2394. if ent.pointer_address:
  2395. for k in PackDict.keys():
  2396. for i in range(len(PackDict[k]["roleList"])):
  2397. if PackDict[k]["roleList"][i].entity_text == ent.entity_text:
  2398. if not PackDict[k]["roleList"][i].address:
  2399. PackDict[k]["roleList"][i].address = ent.pointer_address.entity_text
  2400. last_role_prob[PackDict[k]["roleList"][i].role_name] = ent.values[role2id_dict[PackDict[k]["roleList"][i].role_name]]
  2401. else:
  2402. if PackDict[k]["roleList"][i].role_name in ['tenderee','agency']:
  2403. # 角色为招标/代理人时,取其实体概率高的链接地址作为角色address
  2404. if ent.values[role2id_dict[PackDict[k]["roleList"][i].role_name]] > last_role_prob[PackDict[k]["roleList"][i].role_name]:
  2405. PackDict[k]["roleList"][i].address = ent.pointer_address.entity_text
  2406. last_role_prob[PackDict[k]["roleList"][i].role_name] = ent.values[role2id_dict[PackDict[k]["roleList"][i].role_name]]
  2407. else:
  2408. if len(ent.pointer_address.entity_text) > len(PackDict[k]["roleList"][i].address):
  2409. PackDict[k]["roleList"][i].address = ent.pointer_address.entity_text
  2410. # 联系人——电子邮箱链接
  2411. temporary_list3 = [entity for entity in list_entity if entity.entity_type=='email' or (entity.entity_type=='person' and entity.label in [1,2,3])]
  2412. temporary_list3 = sorted(temporary_list3, key=lambda x: (x.sentence_index, x.begin_index))
  2413. new_temporary_list3 = []
  2414. for _split in new_split_list:
  2415. temp_list = []
  2416. for _entity in temporary_list3:
  2417. if words_num_dict[_entity.sentence_index] + _entity.wordOffset_begin >= _split[0] and words_num_dict[
  2418. _entity.sentence_index] + _entity.wordOffset_end < _split[1]:
  2419. temp_list.append(_entity)
  2420. elif words_num_dict[_entity.sentence_index] + _entity.wordOffset_begin >= _split[1]:
  2421. break
  2422. new_temporary_list3.append(temp_list)
  2423. # print(new_temporary_list3)
  2424. match_list3 = []
  2425. for split_index in range(len(new_temporary_list3)):
  2426. split_entitys = new_temporary_list3[split_index]
  2427. for index in range(len(split_entitys)):
  2428. entity = split_entitys[index]
  2429. if entity.entity_type == 'person':
  2430. match_nums = 0
  2431. for after_index in range(index + 1, min(len(split_entitys), index + 4)):
  2432. after_entity = split_entitys[after_index]
  2433. if match_nums > 2:
  2434. break
  2435. if after_entity.entity_type == 'email':
  2436. distance = (tokens_num_dict[after_entity.sentence_index] + after_entity.begin_index) - (
  2437. tokens_num_dict[entity.sentence_index] + entity.end_index)
  2438. sentence_distance = after_entity.sentence_index - entity.sentence_index
  2439. if sentence_distance == 0:
  2440. if distance < 100:
  2441. if (entity.label == 0 and after_entity.label == 1) or (
  2442. entity.label == 1 and after_entity.label == 2):
  2443. distance = distance / 100
  2444. value = (-1 / 2 * (distance ** 2)) / 10000
  2445. match_list3.append(Match(entity, after_entity, value))
  2446. match_nums += 1
  2447. else:
  2448. if distance < 60:
  2449. if (entity.label == 0 and after_entity.label == 1) or (
  2450. entity.label == 1 and after_entity.label == 2):
  2451. distance = distance / 100
  2452. value = (-1 / 2 * (distance ** 2)) / 10000
  2453. match_list3.append(Match(entity, after_entity, value))
  2454. match_nums += 1
  2455. # 前向查找匹配
  2456. # if not match_nums:
  2457. if index != 0:
  2458. previous_entity = split_entitys[index - 1]
  2459. if previous_entity.entity_type == 'email':
  2460. if previous_entity.sentence_index == entity.sentence_index:
  2461. distance = (tokens_num_dict[entity.sentence_index] + entity.begin_index) - (
  2462. tokens_num_dict[
  2463. previous_entity.sentence_index] + previous_entity.end_index)
  2464. if distance < 30:
  2465. # 距离相等时,前向添加处罚值
  2466. # distance += 1
  2467. # 前向 没有 /10000
  2468. value = (-1 / 2 * (distance ** 2))
  2469. match_list3.append(Match(entity, previous_entity, value))
  2470. # print(match_list3)
  2471. # km算法分配求解
  2472. result3 = dispatch(match_list3)
  2473. for match in result3:
  2474. match_person = match[0]
  2475. match_email = match[1]
  2476. match_person.pointer_email = match_email
  2477. # # 1)第一个公司实体的招标人,则看看下一个实体是否为代理人,如果是则联系人错位连接 。2)在同一句中往后找联系人。3)连接不上在整个文章找联系人。
  2478. # temp_ent_list = [] # 临时列表,记录0,1角色及3联系人
  2479. # other_person = [] # 阈值以上的联系人列表
  2480. # link_person = [] # 有电话没联系上角色的person列表
  2481. # other_ent = []
  2482. # link_ent = []
  2483. # found_person = False
  2484. # ent_list = []
  2485. # for entity in list_entity:
  2486. # if entity.entity_type in ['org','company','person']:
  2487. # ent_list.append(entity)
  2488. # # ent_list = [entity for entity in list_entity if entity.entity_type in ['org','company','person']]
  2489. # #for list_index in range(len(ent_list)):
  2490. # #if ent_list[list_index].entity_type in ['org','company'] and ent_list[list_index].label == 0 and list_index+2<len(ent_list) and \
  2491. # #ent_list[list_index+1].entity_type in ['org','company'] and ent_list[list_index+1].label == 1 and ent_list[list_index+2].entity_type in ['person']:
  2492. # #ent_list[list_index+1], ent_list[list_index+2] = ent_list[list_index+2], ent_list[list_index+1]
  2493. # # 2020/11/25增加确定角色联系人判断
  2494. # sure_person_set = set([entity.entity_text for entity in ent_list if entity.entity_type == 'person' and entity.label in [1, 2]])
  2495. # # 招标/代理在同一句中交叉情况的处理
  2496. # for index in range(len(ent_list)):
  2497. # entity = ent_list[index]
  2498. # if entity.entity_text in roleSet and entity.label in [0, 1] and index+3<len(ent_list):
  2499. # if entity.sentence_index==ent_list[index+1].sentence_index==ent_list[index+2].sentence_index==ent_list[index+3].sentence_index:
  2500. # if ent_list[index+1].begin_index - entity.end_index < 30:
  2501. # if ent_list[index+1].entity_text in roleSet and ent_list[index+1].label in [0, 1] and entity.label!=ent_list[index+1].label:
  2502. # if ent_list[index+2].entity_type=="person" and ent_list[index+3].entity_type=="person" and \
  2503. # ent_list[index+2].label==3 and ent_list[index+3].label==3:
  2504. # ent_list[index + 1], ent_list[index + 2] = ent_list[index + 2], ent_list[index + 1]
  2505. #
  2506. #
  2507. # for index in range(len(ent_list)):
  2508. # entity = ent_list[index]
  2509. # if entity.entity_type=="person":
  2510. # if str(entity.label) == "0": # 2020/11/25 非联系人直接跳过
  2511. # continue
  2512. # if entity.values[entity.label]>on_value_person:
  2513. # if str(entity.label)=="1":
  2514. # for i in range(len(PackDict["Project"]["roleList"])):
  2515. # if PackDict["Project"]["roleList"][i].role_name=="tenderee":
  2516. # PackDict["Project"]["roleList"][i].linklist.append((entity.entity_text,entity.person_phone))
  2517. # link_person.append(entity.entity_text)
  2518. # link_ent.append(PackDict["Project"]["roleList"][i].entity_text)
  2519. # # add pointer_person
  2520. # for _entity in list_entity:
  2521. # if dict_role_id.get(str(_entity.label))=="tenderee":
  2522. # for i in range(len(PackDict["Project"]["roleList"])):
  2523. # if PackDict["Project"]["roleList"][i].entity_text==_entity.entity_text and PackDict["Project"]["roleList"][i].role_name=="tenderee":
  2524. # _entity.pointer_person = entity
  2525. # elif str(entity.label)=="2":
  2526. # for i in range(len(PackDict["Project"]["roleList"])):
  2527. # if PackDict["Project"]["roleList"][i].role_name=="agency":
  2528. # PackDict["Project"]["roleList"][i].linklist.append((entity.entity_text,entity.person_phone))
  2529. # link_person.append(entity.entity_text)
  2530. # link_ent.append(PackDict["Project"]["roleList"][i].entity_text)
  2531. # # add pointer_person
  2532. # for _entity in list_entity:
  2533. # if dict_role_id.get(str(_entity.label))=="agency":
  2534. # for i in range(len(PackDict["Project"]["roleList"])):
  2535. # if PackDict["Project"]["roleList"][i].entity_text==_entity.entity_text and PackDict["Project"]["roleList"][i].role_name=="agency":
  2536. # _entity.pointer_person = entity
  2537. # elif str(entity.label)=="3":
  2538. # if entity.entity_text in sure_person_set: # 2020/11/25 排除已经确定角色的联系人
  2539. # continue
  2540. # #not_link_person.append((entity_after.entity_text,entity_after.person_phone))
  2541. # other_person.append(entity.entity_text)
  2542. # temp_ent_list.append((entity.entity_text,entity.person_phone,entity))
  2543. #
  2544. # #if entity.entity_text in roleSet:
  2545. # if entity.entity_text in roleSet:
  2546. # if entity.label in [0,1]:
  2547. # other_ent.append(entity.entity_text)
  2548. # temp_ent_list.append((entity.entity_text, entity.label,entity))
  2549. # for behind_index in range(index+1, len(ent_list)):
  2550. # entity_after = ent_list[behind_index]
  2551. # if entity_after.sentence_index-entity.sentence_index>=1 or entity_after.entity_type in ['org','company']: # 只在本句中找联系人
  2552. # break
  2553. # if entity_after.values is not None:
  2554. # if entity_after.entity_type=="person":
  2555. # if str(entity_after.label) == "0": # 2020/11/25角色后面为非联系人 停止继续往后找
  2556. # break
  2557. # if entity_after.values[entity_after.label]>on_value_person:
  2558. # if str(entity_after.label)=="1":
  2559. # for i in range(len(PackDict["Project"]["roleList"])):
  2560. # if PackDict["Project"]["roleList"][i].role_name=="tenderee":
  2561. # PackDict["Project"]["roleList"][i].linklist.append((entity_after.entity_text,entity_after.person_phone))
  2562. # link_person.append(entity_after.entity_text)
  2563. # link_ent.append(PackDict["Project"]["roleList"][i].entity_text)
  2564. # elif str(entity_after.label)=="2":
  2565. # for i in range(len(PackDict["Project"]["roleList"])):
  2566. # if PackDict["Project"]["roleList"][i].role_name=="agency":
  2567. # PackDict["Project"]["roleList"][i].linklist.append((entity_after.entity_text,entity_after.person_phone))
  2568. # link_person.append(entity_after.entity_text)
  2569. # link_ent.append(PackDict["Project"]["roleList"][i].entity_text)
  2570. # elif str(entity_after.label)=="3":
  2571. # if entity_after.entity_text in sure_person_set: # 2020/11/25 如果姓名已经出现在确定角色联系人中则停止往后找
  2572. # break
  2573. # elif entity_after.begin_index - entity.end_index > 30:#2020/10/25 如果角色实体与联系人实体间隔大于阈值停止
  2574. # break
  2575. # for pack in PackDict.keys():
  2576. # for i in range(len(PackDict[pack]["roleList"])):
  2577. # if PackDict[pack]["roleList"][i].entity_text==entity.entity_text:
  2578. # #if entity_after.sentence_index-entity.sentence_index>1 and len(roleList[i].linklist)>0:
  2579. # #break
  2580. # PackDict[pack]["roleList"][i].linklist.append((entity_after.entity_text,entity_after.person_phone))
  2581. # link_person.append(entity_after.entity_text)
  2582. # #add pointer_person
  2583. # entity.pointer_person = entity_after
  2584. #
  2585. # not_link_person = [person for person in other_person if person not in link_person]
  2586. # not_link_ent = [ent for ent in other_ent if ent not in link_ent]
  2587. # if len(not_link_person) > 0 and len(not_link_ent) > 0 :
  2588. # item = temp_ent_list
  2589. # for i in range(len(item)):
  2590. # if item[i][0] in not_link_ent and item[i][1] == 0 and i+3 < len(item):
  2591. # if item[i+1][0] in other_ent and item[i+1][1] == 1 and item[i+2][0] in other_person and item[i+3][0] in other_person:
  2592. # item[i+1], item[i+2] = item[i+2], item[i+1]
  2593. # for i in range(len(item)-1, -1, -1):
  2594. # if item[i][0] in not_link_ent:
  2595. # for pack in PackDict.keys():
  2596. # for role in PackDict[pack]["roleList"]:
  2597. # if role.entity_text == item[i][0] and len(role.linklist) < 1:
  2598. # for j in range(i+1, len(item)):
  2599. # if item[j][0] in not_link_person:
  2600. # role.linklist.append(item[j][:2])
  2601. # #add pointer_person
  2602. # item[i][2].pointer_person = item[j][2]
  2603. # break
  2604. # else:
  2605. # break
  2606. # # 电话没有联系人的处理
  2607. # role_with_no_phone = []
  2608. # for i in range(len(PackDict["Project"]["roleList"])):
  2609. # if PackDict["Project"]["roleList"][i].role_name in ["tenderee","agency"]:
  2610. # if len(PackDict["Project"]["roleList"][i].linklist)==0: # 找出没有联系人的招标/代理人
  2611. # role_with_no_phone.append(PackDict["Project"]["roleList"][i].entity_text)
  2612. # else:
  2613. # phone_nums = 0
  2614. # for link in PackDict["Project"]["roleList"][i].linklist:
  2615. # if link[1]:
  2616. # phone_nums += 1
  2617. # break
  2618. # if not phone_nums:
  2619. # role_with_no_phone.append(PackDict["Project"]["roleList"][i].entity_text)
  2620. # if role_with_no_phone:
  2621. # phone_with_person = [entity.person_phone for entity in list_entity if entity.entity_type == "person"]
  2622. # # phone_with_person = [phone for phone in phone_with_person if phone]
  2623. #
  2624. # dict_index_sentence = {}
  2625. # for _sentence in list_sentence:
  2626. # dict_index_sentence[_sentence.sentence_index] = _sentence
  2627. # new_entity_list = [entity for entity in list_entity if entity.entity_type in ['org','company','person']]
  2628. # for index in range(len(new_entity_list)):
  2629. # entity = new_entity_list[index]
  2630. # if entity.entity_text in role_with_no_phone:
  2631. # e_sentence = dict_index_sentence[entity.sentence_index]
  2632. # entity_right = e_sentence.tokens[entity.end_index:entity.end_index+40]
  2633. # entity_right = "".join(entity_right)
  2634. # if index+1<len(new_entity_list) and entity_right.find(new_entity_list[index+1].entity_text)>-1:
  2635. # entity_right = entity_right[:entity_right.find(new_entity_list[index+1].entity_text)]
  2636. # have_phone = re.findall(phone,entity_right)
  2637. # if have_phone:
  2638. # _phone = have_phone[0]
  2639. # phone_begin = entity_right.find(_phone)
  2640. # if _phone not in phone_with_person and re.search(key_phone,entity_right[:phone_begin]):
  2641. # # entity.person_phone = _phone
  2642. # for i in range(len(PackDict["Project"]["roleList"])):
  2643. # if PackDict["Project"]["roleList"][i].entity_text == entity.entity_text:
  2644. # PackDict["Project"]["roleList"][i].linklist.append(('', _phone))
  2645. #寻找多标段招标金额
  2646. p_entity = len(list_entity)-1
  2647. set_tenderer_money = set()
  2648. list_tenderer_money = [] #2021/7/16 新增列表,倒序保存所有中标金额
  2649. unit_list = [] #2021/8/17 新增,保存金额单位
  2650. #遍历所有实体
  2651. while(p_entity>=0):
  2652. entity = list_entity[p_entity]
  2653. if entity.entity_type=="money":
  2654. # 2021/12/03 添加成本警戒线、保证金
  2655. if entity.notes in ['保证金', '成本警戒线']:
  2656. packagePointer, _flag = getPackage(PackageList, entity.sentence_index, entity.begin_index,
  2657. "money-" + str(entity.label), MAX_DIS=2, DIRECT="L")
  2658. if packagePointer is None:
  2659. packageName = "Project"
  2660. else:
  2661. packageName = packagePointer.entity_text
  2662. if packageName == "Project":
  2663. # if PackDict["Project"]["tendereeMoney"]<float(entity.entity_text):
  2664. # PackDict["Project"]["tendereeMoney"] = float(entity.entity_text)
  2665. if entity.notes=="保证金" and "bond" not in PackDict["Project"]:
  2666. PackDict["Project"]["bond"] = float(entity.entity_text)
  2667. elif entity.notes=="成本警戒线" and "cost_warning" not in PackDict["Project"]:
  2668. PackDict["Project"]["cost_warning"] = float(entity.entity_text)
  2669. else:
  2670. if entity.notes == "保证金" and "bond" not in PackDict[packageName]:
  2671. PackDict[packageName]["bond"] = float(entity.entity_text)
  2672. elif entity.notes == "成本警戒线" and "cost_warning" not in PackDict[packageName]:
  2673. PackDict[packageName]["cost_warning"] = float(entity.entity_text)
  2674. elif entity.values[entity.label]>=on_value:
  2675. if str(entity.label)=="1":
  2676. set_tenderer_money.add(float(entity.entity_text))
  2677. list_tenderer_money.append(float(entity.entity_text)) # 2021/7/16 新增列表,倒序保存所有中标金额
  2678. unit_list.append(entity.money_unit)
  2679. # if str(entity.label)=="0":
  2680. if str(entity.label)=="0" and entity.notes!='总投资':
  2681. '''
  2682. if p_entity>0:
  2683. p_before = list_entity[p_entity-1]
  2684. if p_before.entity_type=="money" and p_before.label==entity.label and p_before.entity_text==entity.entity_text and abs(entity.begin_index-p_before.end_index)<=2:
  2685. p_entity -= 1
  2686. continue
  2687. '''
  2688. packagePointer,_flag = getPackage(PackageList,entity.sentence_index,entity.begin_index,"money-"+str(entity.label),MAX_DIS=2,DIRECT="L")
  2689. if packagePointer is None:
  2690. packageName = "Project"
  2691. else:
  2692. packageName = packagePointer.entity_text
  2693. if packageName=="Project":
  2694. # if PackDict["Project"]["tendereeMoney"]<float(entity.entity_text):
  2695. # PackDict["Project"]["tendereeMoney"] = float(entity.entity_text)
  2696. if entity.values[entity.label]>on_value:
  2697. PackDict["Project"]["tendereeMoney"] = float(entity.entity_text)
  2698. PackDict["Project"]["tendereeMoneyUnit"] = entity.money_unit
  2699. else:
  2700. PackDict[packageName]["tendereeMoney"] = float(entity.entity_text)
  2701. PackDict[packageName]["tendereeMoneyUnit"] = entity.money_unit
  2702. #add pointer_tendereeMoney
  2703. packagePointer.pointer_tendereeMoney = entity
  2704. p_entity -= 1
  2705. #删除一个机构有多个角色的数据
  2706. #删除重复人、概率不回传
  2707. final_roleList = []
  2708. list_pop = []
  2709. set_tenderer_role = set()
  2710. dict_pack_tenderer_money = dict()
  2711. for pack in PackDict.keys():
  2712. #删除无效包
  2713. if PackDict[pack]["code"]=="" and PackDict[pack]["tendereeMoney"]==0 and len(PackDict[pack]["roleList"])==0:
  2714. list_pop.append(pack)
  2715. for i in range(len(PackDict[pack]["roleList"])):
  2716. if PackDict[pack]["roleList"][i].role_name=="win_tenderer":
  2717. if PackDict[pack]["roleList"][i].money==0:
  2718. set_tenderer_role.add(PackDict[pack]["roleList"][i])
  2719. dict_pack_tenderer_money[pack] = [PackDict[pack]["roleList"][i],set()]
  2720. #找到包的中投标金额
  2721. for _index in range(len(PackageList)):
  2722. if "hit" in PackageList[_index]:
  2723. for _hit in list(PackageList[_index]["hit"]):
  2724. if len(_hit.split("-"))==3:
  2725. _money = float(_hit.split("-")[1]) if _hit.split("-")[0]=="money" else None
  2726. # 补充金额前新增负号‘-’导致错误的规则
  2727. elif len(_hit.split("-"))==4:
  2728. _money = float(_hit.split("-")[2]) if _hit.split("-")[0] == "money" else None
  2729. else:
  2730. _money = None
  2731. if PackageList[_index]["name"] in dict_pack_tenderer_money and _money is not None:
  2732. dict_pack_tenderer_money[PackageList[_index]["name"]][1].add(_money)
  2733. #只找到一个中标人和中标金额
  2734. if len(set_tenderer_money)==1 and len(set_tenderer_role)==1:
  2735. list(set_tenderer_role)[0].money = list(set_tenderer_money)[0]
  2736. list(set_tenderer_role)[0].money_unit = unit_list[0]
  2737. # print('一个中标人一个金额:', list(set_tenderer_money)[0])
  2738. #找到一个中标人和多个招标金额
  2739. if len(set_tenderer_money)>1 and len(set_tenderer_role)==1:
  2740. _maxMoney = list(set_tenderer_money)[0]
  2741. _sumMoney = 0
  2742. for _m in list(set_tenderer_money):
  2743. _sumMoney += _m
  2744. if _m>_maxMoney:
  2745. _maxMoney = _m
  2746. if _sumMoney/_maxMoney==2:
  2747. list(set_tenderer_role)[0].money = _maxMoney
  2748. # print('一人多金额分项合计 取最大金额:', _maxMoney)
  2749. else:
  2750. # list(set_tenderer_role)[0].money = _maxMoney
  2751. if min(list_tenderer_money)>200000 and list_tenderer_money[-1]/min(list_tenderer_money)>9000:
  2752. list(set_tenderer_role)[0].money = min(list_tenderer_money)
  2753. list(set_tenderer_role)[0].money_unit = unit_list[list_tenderer_money.index(min(list_tenderer_money))]
  2754. # print('一人多金额 且最小的大于20万第一个金额比最小金额大几千倍的最小中标金额:', min(list_tenderer_money))
  2755. else:
  2756. list(set_tenderer_role)[0].money = list_tenderer_money[-1] # 2021/7/16 修改 不是单价合计方式取第一个中标金额
  2757. list(set_tenderer_role)[0].money_unit = unit_list[-1] # 金额单位
  2758. # print('一人多金额 取第一个中标金额:', list_tenderer_money[-1])
  2759. #每个包都只找到一个金额
  2760. _flag_pack_money = True
  2761. for k,v in dict_pack_tenderer_money.items():
  2762. if len(v[1])!=1:
  2763. _flag_pack_money = False
  2764. if _flag_pack_money and len(PackageSet)==len(dict_pack_tenderer_money.keys()):
  2765. for k,v in dict_pack_tenderer_money.items():
  2766. v[0].money = list(v[1])[0]
  2767. # print('k,v in dict_pack_tenderer_money.items', k, v)
  2768. # 2021/7/16 #增加判断中标金额是否远大于招标金额逻辑
  2769. for pack in PackDict.keys():
  2770. for i in range(len(PackDict[pack]["roleList"])):
  2771. if PackDict[pack]["tendereeMoney"] > 0:
  2772. # print('金额数据类型:',type(PackDict[pack]["roleList"][i].money))
  2773. if float(PackDict[pack]["roleList"][i].money) >10000000 and \
  2774. float(PackDict[pack]["roleList"][i].money)/float(PackDict[pack]["tendereeMoney"])>=1000:
  2775. PackDict[pack]["roleList"][i].money = float(PackDict[pack]["roleList"][i].money) / 10000
  2776. # print('招标金额校正中标金额')
  2777. # 2022/04/01 #增加判断中标金额是否远小于招标金额逻辑,比例相差10000倍左右(中标金额“万”单位丢失或未识别)
  2778. for pack in PackDict.keys():
  2779. for i in range(len(PackDict[pack]["roleList"])):
  2780. if PackDict[pack]["tendereeMoney"] > 0 and float(PackDict[pack]["roleList"][i].money) > 0.:
  2781. if float(PackDict[pack]["roleList"][i].money) < 1000 and \
  2782. float(PackDict[pack]["tendereeMoney"])/float(PackDict[pack]["roleList"][i].money)>=9995 and \
  2783. float(PackDict[pack]["tendereeMoney"])/float(PackDict[pack]["roleList"][i].money)<11000:
  2784. PackDict[pack]["roleList"][i].money = float(PackDict[pack]["roleList"][i].money) * 10000
  2785. # 2021/7/19 #增加判断中标金额是否远大于第二三中标金额
  2786. for pack in PackDict.keys():
  2787. tmp_moneys = []
  2788. for i in range(len(PackDict[pack]["roleList"])):
  2789. if float(PackDict[pack]["roleList"][i].money) >100000:
  2790. tmp_moneys.append(float(PackDict[pack]["roleList"][i].money))
  2791. if len(tmp_moneys)>2 and max(tmp_moneys)/min(tmp_moneys)>1000:
  2792. for i in range(len(PackDict[pack]["roleList"])):
  2793. if float(PackDict[pack]["roleList"][i].money)/min(tmp_moneys)>1000:
  2794. PackDict[pack]["roleList"][i].money = float(PackDict[pack]["roleList"][i].money) / 10000
  2795. # print('通过其他中标人投标金额校正中标金额')
  2796. for item in list_pop:
  2797. PackDict.pop(item)
  2798. # 公告中只有"招标人"且无"联系人"链接时
  2799. if len(PackDict)==1:
  2800. k = list(PackDict.keys())[0]
  2801. if len(PackDict[k]["roleList"])==1:
  2802. if PackDict[k]["roleList"][0].role_name == "tenderee":
  2803. if not PackDict[k]["roleList"][0].linklist:
  2804. get_contacts = False
  2805. if not get_contacts:
  2806. # 根据大纲Outline类召回联系人
  2807. for outline in list_outline:
  2808. if re.search("联系人|联系方|联系方式|联系电话|电话|负责人|与.{2,4}联系",outline.outline_summary):
  2809. for t_person in [p for p in temporary_list2 if p.entity_type=='person' and p.label==3]:
  2810. if words_num_dict[t_person.sentence_index] + t_person.wordOffset_begin >= words_num_dict[outline.sentence_begin_index] + outline.wordOffset_begin and words_num_dict[
  2811. t_person.sentence_index] + t_person.wordOffset_end < words_num_dict[outline.sentence_end_index] + outline.wordOffset_end:
  2812. if t_person.person_phone:
  2813. _phone = [p.entity_text for p in t_person.person_phone]
  2814. for _p in _phone:
  2815. PackDict[k]["roleList"][0].linklist.append((t_person.entity_text, _p))
  2816. get_contacts = True
  2817. break
  2818. elif words_num_dict[t_person.sentence_index] + t_person.wordOffset_begin >= \
  2819. words_num_dict[outline.sentence_end_index] + outline.wordOffset_end:
  2820. break
  2821. if not get_contacts:
  2822. sentence_phone = phone.findall(outline.outline_text)
  2823. if sentence_phone:
  2824. PackDict[k]["roleList"][0].linklist.append(("", sentence_phone[0]))
  2825. get_contacts = True
  2826. break
  2827. if not get_contacts:
  2828. # 直接取文中倒数第一个联系人
  2829. for _entity in temporary_list2[::-1]:
  2830. if _entity.entity_type=='person' and _entity.label==3:
  2831. if _entity.person_phone:
  2832. _phone = [p.entity_text for p in _entity.person_phone]
  2833. for _p in _phone:
  2834. PackDict[k]["roleList"][0].linklist.append((_entity.entity_text, _p))
  2835. get_contacts = True
  2836. break
  2837. if not get_contacts:
  2838. # 如果文中只有一个“phone”实体,则直接取为联系人电话
  2839. if len(phone_entitys) == 1:
  2840. PackDict[k]["roleList"][0].linklist.append(("", phone_entitys[0].entity_text))
  2841. get_contacts = True
  2842. if not get_contacts:
  2843. # 通过大纲Outline类直接取电话
  2844. if len(new_split_list) > 1:
  2845. for _start, _end in new_split_list:
  2846. temp_sentence = _content[_start:_end]
  2847. sentence_outline = temp_sentence.split(",::")[0]
  2848. if re.search("联系人|联系方|联系方式|联系电话|电话|负责人|与.{2,4}联系", sentence_outline):
  2849. sentence_phone = phone.findall(temp_sentence)
  2850. if sentence_phone:
  2851. if sentence_phone[0] in [ent.entity_text for ent in phone_entitys]:
  2852. PackDict[k]["roleList"][0].linklist.append(("", sentence_phone[0]))
  2853. get_contacts = True
  2854. break
  2855. if not get_contacts:
  2856. # 通过正则提取句子段落进行提取电话
  2857. contacts_person = "(?:联系人|联系方|联系方式|负责人|电话|联系电话)[::]?"
  2858. tenderee_pattern = "(?:(?:采购|招标|议价|议标|比选)(?:人|公司|单位|组织|部门)|建设(?:单位|业主)|(?:采购|招标|甲)方|询价单位|项目业主|业主|业主单位)[^。]{0,5}"
  2859. contact_pattern_list = [tenderee_pattern + contacts_person,
  2860. "(?:采购[^。,]{0,2}项目|采购事项|招标)[^。,]{0,4}" + contacts_person,
  2861. "(?:项目|采购)[^。,]{0,4}" + contacts_person,
  2862. "(?:报名|报价|业务咨询|业务|投标咨询)[^。,]{0,4}" + contacts_person, ]
  2863. for _pattern in contact_pattern_list:
  2864. get_tenderee_contacts = False
  2865. for regular_match in re.finditer(_pattern, _content):
  2866. match_text = _content[regular_match.end():regular_match.end() + 40]
  2867. match_text = match_text.split("。")[0]
  2868. sentence_phone = phone.findall(match_text)
  2869. if sentence_phone:
  2870. PackDict[k]["roleList"][0].linklist.append(("", sentence_phone[0]))
  2871. get_tenderee_contacts = True
  2872. break
  2873. if get_tenderee_contacts:
  2874. break
  2875. for pack in PackDict.keys():
  2876. for i in range(len(PackDict[pack]["roleList"])):
  2877. PackDict[pack]["roleList"][i] = PackDict[pack]["roleList"][i].getString()
  2878. return PackDict
  2879. def initPackageAttr(RoleList,PackageSet):
  2880. '''
  2881. @summary: 根据拿到的roleList和packageSet初始化接口返回的数据
  2882. '''
  2883. packDict = dict()
  2884. packDict["Project"] = {"code":"","tendereeMoney":0,"roleList":[], 'tendereeMoneyUnit':''}
  2885. for item in list(PackageSet):
  2886. packDict[item] = {"code":"","tendereeMoney":0,"roleList":[], 'tendereeMoneyUnit':''}
  2887. for item in RoleList:
  2888. if packDict[item.packageName]["code"] =="":
  2889. packDict[item.packageName]["code"] = item.packageCode
  2890. # packDict[item.packageName]["roleList"].append(Role(item.role_name,item.entity_text,0,0,0.0,[]))
  2891. packDict[item.packageName]["roleList"].append(Role(item.role_name,item.entity_text,0,0,0.0,[])) #Role(角色名称,实体名称,角色阈值,金额,金额阈值,连接列表,金额单位)
  2892. return packDict
  2893. def getPackageRoleMoney(list_sentence,list_entity,list_outline):
  2894. '''
  2895. @param:
  2896. list_sentence:文章的句子list
  2897. list_entity:文章的实体list
  2898. @return: 拿到文章的包-标段号-角色-实体名称-金额-联系人-联系电话
  2899. '''
  2900. # print("=1")
  2901. theRole = getRoleList(list_sentence,list_entity)
  2902. if not theRole:
  2903. return []
  2904. RoleList,RoleSet,PackageList,PackageSet = theRole
  2905. '''
  2906. for item in PackageList:
  2907. # print(item)
  2908. '''
  2909. PackDict = initPackageAttr(RoleList, PackageSet)
  2910. PackDict = findAttributeAfterEntity(PackDict, RoleSet, PackageList, PackageSet, list_sentence, list_entity, list_outline)
  2911. return PackDict
  2912. def turnBidWay(bidway):
  2913. if bidway in ("邀请招标","采购方式:邀请"):
  2914. return "邀请招标"
  2915. elif bidway in ("询价","询单","询比","采购方式:询价"):
  2916. return "询价"
  2917. elif bidway in ("竞谈","竞争性谈判","公开竞谈"):
  2918. return "竞争性谈判"
  2919. elif bidway in ("竞争性磋商","磋商"):
  2920. return "竞争性磋商"
  2921. elif bidway in ("竞价","竞标","电子竞价","以电子竞价","电子书面竞投"):
  2922. return "竞价"
  2923. elif bidway in ("公开招标","网上电子投标","网上招标","采购方式:公开","招标为其他"):
  2924. return "公开招标"
  2925. elif bidway in ("单一来源"):
  2926. return "单一来源"
  2927. elif bidway in ("比选"):
  2928. return "比选"
  2929. else:
  2930. return "其他"
  2931. my_time_format_pattern = re.compile("((?P<year>\d{4}|\d{2})\s*[-\/年\.]\s*(?P<month>\d{1,2})\s*[-\/月\.]\s*(?P<day>\d{1,2}))")
  2932. import time
  2933. def my_timeFormat(_time):
  2934. current_year = time.strftime("%Y",time.localtime())
  2935. all_match = re.finditer(my_time_format_pattern,_time)
  2936. time_list = []
  2937. for _match in all_match:
  2938. if len(_match.group())>0:
  2939. legal = True
  2940. year = ""
  2941. month = ""
  2942. day = ""
  2943. for k,v in _match.groupdict().items():
  2944. if k=="year":
  2945. year = v
  2946. if k=="month":
  2947. month = v
  2948. if k=="day":
  2949. day = v
  2950. if year!="":
  2951. if len(year)==2:
  2952. year = "20"+year
  2953. if int(year)>int(current_year):
  2954. legal = False
  2955. else:
  2956. legal = False
  2957. if month!="":
  2958. if int(month)>12:
  2959. legal = False
  2960. else:
  2961. legal = False
  2962. if day!="":
  2963. if int(day)>31:
  2964. legal = False
  2965. else:
  2966. legal = False
  2967. if legal:
  2968. # return "%s-%s-%s"%(year,month.rjust(2,"0"),day.rjust(2,"0"))
  2969. time_list.append("%s-%s-%s"%(year,month.rjust(2,"0"),day.rjust(2,"0")))
  2970. return time_list
  2971. def getTimeAttributes(list_entity,list_sentence):
  2972. time_entitys = [i for i in list_entity if i.entity_type=='time']
  2973. time_entitys = sorted(time_entitys,key=lambda x:(x.sentence_index, x.begin_index))
  2974. list_sentence = sorted(list_sentence,key=lambda x:x.sentence_index)
  2975. dict_time = {
  2976. "time_release": [], # 1 发布时间
  2977. "time_bidopen": [], # 2 开标时间
  2978. "time_bidclose": [], # 3 截标时间
  2979. 'time_bidstart': [], # 12 投标(开始)时间、响应文件接收(开始)时间
  2980. 'time_publicityStart': [], # 4 公示开始时间(公示时间、公示期)
  2981. 'time_publicityEnd': [], # 5 公示截止时间
  2982. 'time_getFileStart': [], # 6 文件获取开始时间(文件获取时间)
  2983. 'time_getFileEnd': [], # 7 文件获取截止时间
  2984. 'time_registrationStart': [], # 8 报名开始时间(报名时间)
  2985. 'time_registrationEnd': [], # 9 报名截止时间
  2986. 'time_earnestMoneyStart': [], #10 保证金递交开始时间(保证金递交时间)
  2987. 'time_earnestMoneyEnd': [] , # 11 保证金递交截止时间
  2988. 'time_commencement':[] , #13 开工日期
  2989. 'time_completion': [], # 14 竣工日期
  2990. 'time_listingStart': [], # 15 挂牌开始日期(挂牌时间)
  2991. 'time_listingEnd': [] # 16 挂牌结束日期、挂牌截止日期
  2992. }
  2993. last_sentence_index = 0
  2994. last_time_type = ""
  2995. last_time_index = {
  2996. 'time_bidstart':"time_bidclose",
  2997. 'time_publicityStart':"time_publicityEnd",
  2998. 'time_getFileStart':"time_getFileEnd",
  2999. 'time_registrationStart':"time_registrationEnd",
  3000. 'time_earnestMoneyStart':"time_earnestMoneyEnd",
  3001. 'time_commencement':"time_completion",
  3002. 'time_listingStart':"time_listingEnd"
  3003. }
  3004. for entity in time_entitys:
  3005. sentence_text = list_sentence[entity.sentence_index].sentence_text
  3006. entity_left = sentence_text[max(0, entity.wordOffset_begin - 2):entity.wordOffset_begin]
  3007. entity_left2 = sentence_text[max(0, entity.wordOffset_begin - 10):entity.wordOffset_begin]
  3008. entity_right = sentence_text[entity.wordOffset_end:entity.wordOffset_end + 3]
  3009. label_prob = entity.values[entity.label]
  3010. entity_text = entity.entity_text
  3011. in_attachment = entity.in_attachment
  3012. extract_time = my_timeFormat(entity_text)
  3013. if extract_time:
  3014. # 2022/12/12 新增挂牌时间正则
  3015. if re.search("挂牌.{,4}(?:时间|日期)",entity_left2):
  3016. if re.search("挂牌.{,4}(?:时间|日期)",entity_left2).end()>len(entity_left2)/2:
  3017. if len(extract_time) == 1:
  3018. if re.search("挂牌.?(开始|起始).?(?:时间|日期)",entity_left2):
  3019. dict_time['time_listingStart'].append((extract_time[0], 0.5, in_attachment))
  3020. last_time_type = 'time_listingStart'
  3021. elif re.search("挂牌.?(截[止至]|结束).?(?:时间|日期)",entity_left2):
  3022. dict_time['time_listingEnd'].append((extract_time[0], 0.5, in_attachment))
  3023. last_time_type = 'time_listingEnd'
  3024. elif re.search("挂牌.?(?:时间|日期)",entity_left2):
  3025. if re.search("前|止|截止",entity_right) or re.search("至|止|到",entity_left) or re.search("前",entity_text[-2:]):
  3026. dict_time['time_listingEnd'].append((extract_time[0], 0.5, in_attachment))
  3027. last_time_type = 'time_listingEnd'
  3028. else:
  3029. dict_time['time_listingStart'].append((extract_time[0], 0.5, in_attachment))
  3030. last_time_type = 'time_listingStart'
  3031. else:
  3032. dict_time['time_listingStart'].append((extract_time[0], 0.5, in_attachment))
  3033. dict_time['time_listingEnd'].append((extract_time[1], 0.5, in_attachment))
  3034. last_time_type = ''
  3035. last_sentence_index = entity.sentence_index
  3036. continue
  3037. if re.search("至|到", entity_left):
  3038. if entity.sentence_index == last_sentence_index:
  3039. time_type = last_time_index.get(last_time_type)
  3040. if time_type:
  3041. dict_time[time_type].append((extract_time[0], 0.5 + label_prob / 10,in_attachment))
  3042. last_time_type = ""
  3043. last_sentence_index = entity.sentence_index
  3044. continue
  3045. if entity.label!=0:
  3046. if entity.label==1 and label_prob>0.5:
  3047. dict_time['time_release'].append((extract_time[0],label_prob,in_attachment))
  3048. last_time_type = 'time_release'
  3049. elif entity.label==2 and label_prob>0.5:
  3050. dict_time['time_bidopen'].append((extract_time[0],label_prob,in_attachment))
  3051. last_time_type = 'time_bidopen'
  3052. elif entity.label==3 and label_prob>0.5:
  3053. dict_time['time_bidclose'].append((extract_time[0],label_prob,in_attachment))
  3054. last_time_type = 'time_bidclose'
  3055. elif entity.label==12 and label_prob>0.5:
  3056. if len(extract_time)==1:
  3057. if re.search("前|止|截止",entity_right) or re.search("至|止|到",entity_left) or re.search("前",entity_text[-2:]):
  3058. dict_time['time_bidclose'].append((extract_time[0], label_prob,in_attachment))
  3059. last_time_type = 'time_bidclose'
  3060. else:
  3061. dict_time['time_bidstart'].append((extract_time[0], label_prob,in_attachment))
  3062. last_time_type = 'time_bidstart'
  3063. else:
  3064. dict_time['time_bidstart'].append((extract_time[0],label_prob,in_attachment))
  3065. dict_time['time_bidclose'].append((extract_time[1],label_prob,in_attachment))
  3066. last_time_type = ''
  3067. elif entity.label==4 and label_prob>0.5:
  3068. if len(extract_time)==1:
  3069. if re.search("前|止|截止",entity_right) or re.search("至|止|到",entity_left) or re.search("前",entity_text[-2:]):
  3070. dict_time['time_publicityEnd'].append((extract_time[0], label_prob,in_attachment))
  3071. last_time_type = 'time_publicityEnd'
  3072. else:
  3073. dict_time['time_publicityStart'].append((extract_time[0], label_prob,in_attachment))
  3074. last_time_type = 'time_publicityStart'
  3075. else:
  3076. dict_time['time_publicityStart'].append((extract_time[0],label_prob,in_attachment))
  3077. dict_time['time_publicityEnd'].append((extract_time[1],label_prob,in_attachment))
  3078. last_time_type = ''
  3079. elif entity.label==5 and label_prob>0.5:
  3080. if len(extract_time)==1:
  3081. dict_time['time_publicityEnd'].append((extract_time[0], label_prob,in_attachment))
  3082. last_time_type = 'time_publicityEnd'
  3083. else:
  3084. dict_time['time_publicityStart'].append((extract_time[0],label_prob,in_attachment))
  3085. dict_time['time_publicityEnd'].append((extract_time[1],label_prob,in_attachment))
  3086. last_time_type = ''
  3087. elif entity.label==6 and label_prob>0.5:
  3088. if len(extract_time)==1:
  3089. if re.search("前|止|截止",entity_right) or re.search("至|止|到",entity_left) or re.search("前",entity_text[-2:]):
  3090. dict_time['time_getFileEnd'].append((extract_time[0], label_prob,in_attachment))
  3091. last_time_type = 'time_getFileEnd'
  3092. else:
  3093. dict_time['time_getFileStart'].append((extract_time[0], label_prob,in_attachment))
  3094. last_time_type = 'time_getFileStart'
  3095. else:
  3096. dict_time['time_getFileStart'].append((extract_time[0],label_prob,in_attachment))
  3097. dict_time['time_getFileEnd'].append((extract_time[1],label_prob,in_attachment))
  3098. last_time_type = ''
  3099. elif entity.label==7 and label_prob>0.5:
  3100. if len(extract_time)==1:
  3101. dict_time['time_getFileEnd'].append((extract_time[0], label_prob,in_attachment))
  3102. last_time_type = 'time_getFileEnd'
  3103. else:
  3104. dict_time['time_getFileStart'].append((extract_time[0],label_prob,in_attachment))
  3105. dict_time['time_getFileEnd'].append((extract_time[1],label_prob,in_attachment))
  3106. last_time_type = ''
  3107. elif entity.label==8 and label_prob>0.5:
  3108. if len(extract_time)==1:
  3109. if re.search("前|止|截止",entity_right) or re.search("至|止|到",entity_left) or re.search("前",entity_text[-2:]):
  3110. dict_time['time_registrationEnd'].append((extract_time[0], label_prob,in_attachment))
  3111. last_time_type = 'time_registrationEnd'
  3112. else:
  3113. dict_time['time_registrationStart'].append((extract_time[0], label_prob,in_attachment))
  3114. last_time_type = 'time_registrationStart'
  3115. else:
  3116. dict_time['time_registrationStart'].append((extract_time[0],label_prob,in_attachment))
  3117. dict_time['time_registrationEnd'].append((extract_time[1],label_prob,in_attachment))
  3118. last_time_type = ''
  3119. elif entity.label==9 and label_prob>0.5:
  3120. if len(extract_time)==1:
  3121. dict_time['time_registrationEnd'].append((extract_time[0], label_prob,in_attachment))
  3122. last_time_type = 'time_registrationEnd'
  3123. else:
  3124. dict_time['time_registrationStart'].append((extract_time[0],label_prob,in_attachment))
  3125. dict_time['time_registrationEnd'].append((extract_time[1],label_prob,in_attachment))
  3126. last_time_type = ''
  3127. elif entity.label==10 and label_prob>0.5:
  3128. if len(extract_time)==1:
  3129. if re.search("前|止|截止",entity_right) or re.search("至|止|到",entity_left) or re.search("前",entity_text[-2:]):
  3130. dict_time['time_earnestMoneyEnd'].append((extract_time[0], label_prob,in_attachment))
  3131. last_time_type = 'time_earnestMoneyEnd'
  3132. else:
  3133. dict_time['time_earnestMoneyStart'].append((extract_time[0], label_prob,in_attachment))
  3134. last_time_type = 'time_earnestMoneyStart'
  3135. else:
  3136. dict_time['time_earnestMoneyStart'].append((extract_time[0],label_prob,in_attachment))
  3137. dict_time['time_earnestMoneyEnd'].append((extract_time[1],label_prob,in_attachment))
  3138. last_time_type = ''
  3139. elif entity.label==11 and label_prob>0.5:
  3140. if len(extract_time)==1:
  3141. dict_time['time_earnestMoneyEnd'].append((extract_time[0], label_prob,in_attachment))
  3142. last_time_type = 'time_earnestMoneyEnd'
  3143. else:
  3144. dict_time['time_earnestMoneyStart'].append((extract_time[0],label_prob,in_attachment))
  3145. dict_time['time_earnestMoneyEnd'].append((extract_time[1],label_prob,in_attachment))
  3146. last_time_type = ''
  3147. elif entity.label==13 and label_prob>0.5:
  3148. if len(extract_time)==1:
  3149. if re.search("前|止|截止",entity_right) or re.search("至|止|到",entity_left) or re.search("前",entity_text[-2:]):
  3150. dict_time['time_completion'].append((extract_time[0], label_prob,in_attachment))
  3151. last_time_type = 'time_completion'
  3152. else:
  3153. dict_time['time_commencement'].append((extract_time[0], label_prob,in_attachment))
  3154. last_time_type = 'time_commencement'
  3155. else:
  3156. dict_time['time_commencement'].append((extract_time[0],label_prob,in_attachment))
  3157. dict_time['time_completion'].append((extract_time[1],label_prob,in_attachment))
  3158. last_time_type = ''
  3159. elif entity.label==14 and label_prob>0.5:
  3160. if len(extract_time)==1:
  3161. dict_time['time_completion'].append((extract_time[0], label_prob,in_attachment))
  3162. last_time_type = 'time_completion'
  3163. else:
  3164. dict_time['time_commencement'].append((extract_time[0],label_prob,in_attachment))
  3165. dict_time['time_completion'].append((extract_time[1],label_prob,in_attachment))
  3166. last_time_type = ''
  3167. else:
  3168. last_time_type = ""
  3169. else:
  3170. last_time_type = ""
  3171. else:
  3172. last_time_type = ""
  3173. last_sentence_index = entity.sentence_index
  3174. result_dict = dict((key,"") for key in dict_time.keys())
  3175. for time_type,value in dict_time.items():
  3176. list_time = dict_time[time_type]
  3177. if list_time:
  3178. for in_attachment in [False,True]:
  3179. _list_time = [_time for _time in list_time if _time[2]==in_attachment]
  3180. if _list_time:
  3181. _list_time.sort(key=lambda x:x[1],reverse=True)
  3182. if in_attachment==True and len(result_dict[time_type])>0:
  3183. break
  3184. result_dict[time_type] = _list_time[0][0]
  3185. return result_dict
  3186. def getOtherAttributes(list_entity):
  3187. dict_other = {"moneysource":"",
  3188. "person_review":[],
  3189. "serviceTime":"",
  3190. "product":[],
  3191. "total_tendereeMoney":0,
  3192. "total_tendereeMoneyUnit":''}
  3193. list_serviceTime = []
  3194. for entity in list_entity:
  3195. if entity.entity_type == 'bidway':
  3196. dict_other["bidway"] = turnBidWay(entity.entity_text)
  3197. elif entity.entity_type=='moneysource':
  3198. dict_other["moneysource"] = entity.entity_text
  3199. elif entity.entity_type=='serviceTime':
  3200. if re.search("[^之]日|天|年|月|周|星期", entity.entity_text) or re.search("\d{4}[\-\./]\d{1,2}", entity.entity_text):
  3201. list_serviceTime.append(entity)
  3202. elif entity.entity_type=="person" and entity.label ==4:
  3203. dict_other["person_review"].append(entity.entity_text)
  3204. elif entity.entity_type=='product' and entity.entity_text not in dict_other["product"]: #顺序去重保留
  3205. dict_other["product"].append(entity.entity_text)
  3206. elif entity.entity_type=='money' and entity.notes=='总投资' and dict_other["total_tendereeMoney"]<float(entity.entity_text):
  3207. dict_other["total_tendereeMoney"] = float(entity.entity_text)
  3208. dict_other["total_tendereeMoneyUnit"] = entity.money_unit
  3209. if list_serviceTime:
  3210. list_serviceTime.sort(key=lambda x:x.prob,reverse=True)
  3211. max_prob = list_serviceTime[0].prob
  3212. max_prob_serviceTime = [ent for ent in list_serviceTime if ent.prob==max_prob]
  3213. max_prob_serviceTime.sort(key=lambda x:(x.sentence_index,x.begin_index))
  3214. dict_other["serviceTime"] = max_prob_serviceTime[0].entity_text
  3215. # dict_other["product"] = list(set(dict_other["product"])) # 已在添加时 顺序去重保留
  3216. return dict_other
  3217. def getMoneyRange(RoleList):
  3218. pass
  3219. def getPREMs(list_sentences,list_entitys,list_articles,list_outlines):
  3220. '''
  3221. @param:
  3222. list_sentence:所有文章的句子list
  3223. list_entity:所有文章的实体list
  3224. @return:list of dict which include文章的包-角色-实体名称-金额-联系人-联系电话
  3225. '''
  3226. result = []
  3227. for list_sentence,list_entity,list_article,list_outline in zip(list_sentences,list_entitys,list_articles,list_outlines):
  3228. RoleList = getPackageRoleMoney(list_sentence,list_entity,list_outline)
  3229. result.append(dict({"prem": RoleList, "docid": list_article.doc_id},
  3230. **getTimeAttributes(list_entity, list_sentence),
  3231. **{"fingerprint": list_article.fingerprint,
  3232. "match_enterprise": list_article.match_enterprise,
  3233. "match_enterprise_type": list_article.match_enterprise_type,
  3234. "process_time": getCurrent_date(),
  3235. "attachmentTypes": list_article.attachmentTypes, "bidway": list_article.bidway}))
  3236. # result.append(dict({"prem":RoleList,"docid":list_article.doc_id},**getOtherAttributes(list_entity),**getTimeAttributes(list_entity,list_sentence),
  3237. # **{"fingerprint":list_article.fingerprint,"match_enterprise":list_article.match_enterprise,
  3238. # "match_enterprise_type":list_article.match_enterprise_type,"process_time":getCurrent_date(),
  3239. # "attachmentTypes":list_article.attachmentTypes, "bidway": list_article.bidway}))
  3240. return result
  3241. def correct_rolemoney(prem, total_product_money): # 2022/9/26修改为 中标金额小于表格单价数量合计总金额十分之一时替换
  3242. if total_product_money>0 and len(prem[0]['prem'])==1:
  3243. for value in prem[0]['prem'].values():
  3244. for l in value['roleList']:
  3245. try:
  3246. # if l[0] == 'win_tenderer' and float(l[2])<total_product_money:
  3247. # l[2] = total_product_money
  3248. # log('修改中标金额为所有产品总金额')
  3249. if l["role_name"] == 'win_tenderer' and float(l["role_money"]['money'])<total_product_money/10:
  3250. l["role_money"]['money'] = total_product_money
  3251. # log('修改中标金额为所有产品总金额')
  3252. except Exception as e:
  3253. print('表格产品价格修正中标价格报错:%s'%e)
  3254. def limit_maximum_amount(prem, industry):
  3255. indu = industry['industry'].get('class_name', '')
  3256. indu_amount = {
  3257. '计算机设备': 200000000,
  3258. '办公设备': 100000000,
  3259. '家具用具': 500000000,
  3260. '办公消耗用品及类似物品': 100000000,
  3261. '日杂用品': 100000000,
  3262. '餐饮业': 1000000000,
  3263. '物业管理': 1000000000,
  3264. '工程技术与设计服务': 1000000000,
  3265. '工程评价服务': 100000000,
  3266. '其他工程服务': 100000000,
  3267. '工程监理服务': 100000000,
  3268. '工程造价服务': 100000000,
  3269. '会计、审计及税务服务': 100000000,
  3270. }
  3271. if indu in indu_amount:
  3272. maximum_amount = indu_amount[indu]
  3273. try:
  3274. for value in prem[0]['prem'].values():
  3275. for l in value['roleList']:
  3276. if l["role_name"] == 'win_tenderer' and float(l["role_money"]['money']) > maximum_amount:
  3277. if indu in ['餐饮业', '物业管理']:
  3278. l["role_money"]['money'] = str(float(l["role_money"]['money'])/10000)
  3279. elif l["role_money"]['money_unit'] == '万元':
  3280. l["role_money"]['money'] = str(float(l["role_money"]['money'])/10000)
  3281. if float(value['tendereeMoney']) > maximum_amount:
  3282. if indu in ['餐饮业', '物业管理']:
  3283. value['tendereeMoney'] = float(value['tendereeMoney'])/10000
  3284. elif value['tendereeMoneyUnit'] == '万元':
  3285. value['tendereeMoney'] = float(value['tendereeMoney']) / 10000
  3286. except Exception as e:
  3287. print('行业分类限制最高金额抛出异常:%s' % e)
  3288. def get_win_joint(prem, list_entitys, list_sentences, list_articles):
  3289. '''
  3290. 获取联合体信息, 添加到prem
  3291. :param prem:
  3292. :param list_entitys:
  3293. :param list_sentences:
  3294. :param list_articles:
  3295. :return:
  3296. '''
  3297. try:
  3298. if 'win_tenderer' in str(prem) and re.search('联合体:|联合体(成员|单位)[12345一二三四五]?:|(联合体)?成员单位[12345一二三四五]?:|特殊普通合伙:|(联合体)|(联合体(成员|单位)方?[12345一二三四五]?)|((联合体)?成员单位[12345一二三四五]?)|(特殊普通合伙|成员?)', list_articles[0].content):
  3299. sentences = sorted(list_sentences[0], key=lambda x:x.sentence_index)
  3300. for project in prem[0].values():
  3301. if not isinstance(project, dict):
  3302. continue
  3303. for v in project.values():
  3304. for d in v['roleList']:
  3305. if d.get('role_name', '') == 'win_tenderer':
  3306. winner = d.get('role_text')
  3307. join_l = [winner]
  3308. for list_entity in list_entitys:
  3309. for i in range(len(list_entity)-1):
  3310. _entity = list_entity[i]
  3311. b = _entity.wordOffset_begin
  3312. e = _entity.wordOffset_end
  3313. if _entity.entity_type in ['org', 'company'] and _entity.label==2\
  3314. and _entity.entity_text==winner:
  3315. s = sentences[_entity.sentence_index].sentence_text
  3316. for j in range(i+1, len(list_entity)):
  3317. behind_entity = list_entity[j]
  3318. b2 = behind_entity.wordOffset_begin
  3319. e2 = behind_entity.wordOffset_end
  3320. if _entity.sentence_index == behind_entity.sentence_index and behind_entity.entity_type in ['org', 'company'] \
  3321. and b2-e<10 and re.search('联合体:|联合体(成员|单位)[12345一二三四五]?:|(联合体)?成员单位[12345一二三四五]?:|特殊普通合伙:', s[b2-e:b2]) or \
  3322. re.search('(联合体)|(联合体(成员|单位)方?[12345一二三四五]?)|((联合体)?成员单位[12345一二三四五]?)|(特殊普通合伙|成员?)', s[e2:e2+10]):
  3323. join_l.append(behind_entity.entity_text)
  3324. b = b2
  3325. e = e2
  3326. else:
  3327. break
  3328. if len(join_l)>1:
  3329. d['win_tenderer_joint'] = ','.join(join_l)
  3330. # behind_entity = list_entity[i + 1]
  3331. # if _entity.sentence_index== behind_entity.sentence_index and _entity.entity_type in ['org', 'company'] and _entity.label==2\
  3332. # and _entity.entity_text==winner and behind_entity.entity_type in ['org', 'company'] and behind_entity.label==5:
  3333. # s = sentences[_entity.sentence_index].sentence_text
  3334. # b = _entity.wordOffset_begin
  3335. # e = _entity.wordOffset_end
  3336. # b2 = behind_entity.wordOffset_begin
  3337. # e2 = behind_entity.wordOffset_end
  3338. # if re.search('(联合体)', s[e2:e2+6]) and b2-e<3:
  3339. # print('联合体:', s[max(0, b-10):e2+10])
  3340. # d['win_tenderer_joint'] = '%s,%s'%(_entity.entity_text, behind_entity.entity_text)
  3341. # break
  3342. # elif re.search('(联合体((牵头|主办)(人|方|单位)|主体)|牵头(人|方|单位))|(联合体)?成员:|特殊普通合伙:', s[e:b2]) and b2-e<10:
  3343. # d['win_tenderer_joint'] = '%s,%s' % (_entity.entity_text, behind_entity.entity_text)
  3344. # print('联合体:', s[max(0, b - 10):e2 + 10])
  3345. # break
  3346. except Exception as e:
  3347. print('获取联合体抛出异常', e)
  3348. def update_prem(old_prem, new_prem):
  3349. '''
  3350. 根据新旧对比,更新数据
  3351. :param old_prem:
  3352. :param new_prem: 表格提取的要素
  3353. :return:
  3354. '''
  3355. if len(new_prem) >= 1 :
  3356. '''如果表格提取的包大于2,原来的包比表格提取的包多则删除原来多余的包,以表格的为准'''
  3357. if len(new_prem) > 2 and len(old_prem) > len(new_prem):
  3358. del_k = []
  3359. for k in old_prem:
  3360. if k not in new_prem and k != 'Project':
  3361. del_k.append(k)
  3362. for k in del_k:
  3363. old_prem.pop(k)
  3364. for k, v in new_prem.items():
  3365. if k == 'Project':
  3366. if 'Project' in old_prem:
  3367. for d in old_prem['Project']['roleList']:
  3368. for d2 in v['roleList']:
  3369. if d['role_name'] == d2['role_name']:
  3370. d['role_text'] = d2['role_text']
  3371. d['role_money']['money'] = d2['role_money']['money']
  3372. d['role_money']['money_unit'] = d2['role_money']['money_unit']
  3373. v['roleList'].remove(d2)
  3374. for d2 in v['roleList']:
  3375. old_prem['Project']['roleList'].append(d2)
  3376. else:
  3377. old_prem[k] = v
  3378. else:
  3379. if k not in old_prem:
  3380. old_prem[k] = v
  3381. else:
  3382. for d in old_prem[k]['roleList']:
  3383. for d2 in v['roleList']:
  3384. if d['role_name'] == d2['role_name']:
  3385. d['role_text'] = d2['role_text']
  3386. d['role_money']['money'] = d2['role_money']['money']
  3387. d['role_money']['money_unit'] = d2['role_money']['money_unit']
  3388. v['roleList'].remove(d2)
  3389. for d2 in v['roleList']:
  3390. old_prem[k]['roleList'].append(d2)
  3391. # return old_prem
  3392. if __name__=="__main__":
  3393. '''
  3394. conn = getConnection()
  3395. cursor = conn.cursor()
  3396. #sql = " select distinct A.doc_id from entity_mention A,test_predict_role B where A.entity_id=B.entity_id limit 200"
  3397. sql = " select B.doc_id,B.prem from articles_processed A, articles_validation B where A.id=B.doc_id "
  3398. result = []
  3399. cursor.execute(sql)
  3400. rows = cursor.fetchall()
  3401. count = 0
  3402. for row in rows:
  3403. count += 1
  3404. # print(count)
  3405. doc_id = row[0]
  3406. roleList = getPackageRoleMoney(doc_id)
  3407. result.append([doc_id,str(roleList),row[1]])
  3408. ''''''
  3409. with codecs.open("getAttribute.html","w",encoding="utf8") as f:
  3410. f.write('<html><head>\
  3411. <meta http-equiv="Content-Type"\
  3412. content="text/html; charset=UTF-8">\
  3413. </head>\
  3414. <body bgcolor="#FFFFFF">\
  3415. <table border="1">\
  3416. <tr>\
  3417. <td>doc_id</td>\
  3418. <td>角色</td>\
  3419. </tr>')
  3420. for item in result:
  3421. f.write("<tr>"+"<td>"+item[0]+"</td>"+"<td>"+item[1]+"</td>"+"<td>"+item[2]+"</td>"+"</tr>")
  3422. f.write("</table></body>")
  3423. '''