getAttributes.py 202 KB

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