getAttributes.py 248 KB

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