getAttributes.py 206 KB

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