getAttributes.py 202 KB

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