getAttributes.py 129 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304
  1. from BiddingKG.dl.common.Utils import findAllIndex,debug,timeFormat,getCurrent_date
  2. from BiddingKG.dl.interface.Entitys import PREM,Role,Entity
  3. from decimal import Decimal
  4. import re
  5. import copy
  6. import math
  7. import pandas as pd
  8. import os
  9. from scipy.optimize import linear_sum_assignment
  10. from BiddingKG.dl.interface.Entitys import Match
  11. import numpy as np
  12. def getTheRole(entity,role_list):
  13. '''
  14. @summary:根据实体名称拿到index
  15. @param:
  16. entity:实体名称
  17. role_list:角色list
  18. @return:该实体所在下标
  19. '''
  20. for role_index in range(len(role_list)):
  21. if entity in role_list[role_index]:
  22. return role_index
  23. return None
  24. dict_role_id = {"0":"tenderee",
  25. "1":"agency",
  26. "2":"win_tenderer",
  27. "3":"second_tenderer",
  28. "4":"third_tenderer"}
  29. def getPackage(packageList,sentence_index,begin_index,roleid,MAX_DIS=None,DIRECT=None):
  30. '''
  31. @param:
  32. packageList:文章的包的信息,包号-sent_index-词偏移-字偏移-[[前作用域句子,句内偏移],[后作用域句子,句内偏移]]-匹配集合
  33. sentence_index:实体所在的句子
  34. begin_index:实体所在句子的起始位置
  35. @return:公司实体所属的包
  36. @summary: 优化多标段,确定标段作用域之后,寻找作用域包含该实体的所有包,从前往后找到一个还没有该roleid的包返回,若找到的包都有roleid,则返回第一个,若没有找到包,返回None
  37. '''
  38. '''
  39. if len(packageList)==0:
  40. return None
  41. before_index = None
  42. after_index = None
  43. equal_index = None
  44. equal_count = 0
  45. for pack_index in range(len(packageList)):
  46. if packageList[pack_index][1]>sentence_index and after_index is None:
  47. after_index = pack_index
  48. if packageList[pack_index][1]<sentence_index:
  49. before_index = pack_index
  50. if packageList[pack_index][1]==sentence_index and equal_index is None:
  51. equal_index = pack_index
  52. #当前句子和之前句子未找到包
  53. if before_index is None and equal_index is None:
  54. return None
  55. else:
  56. if after_index is None:
  57. end_index = len(packageList)
  58. else:
  59. end_index = after_index
  60. #只在当前句子找到一个包号
  61. if end_index-max((before_index if before_index is not None else -1,equal_index if equal_index is not None else -1))==1:
  62. return packageList[end_index-1][0]
  63. else:
  64. for i in range(max((before_index if before_index is not None else -1,equal_index if equal_index is not None else -1)),end_index):
  65. if packageList[i][2]>int(begin_index):
  66. if packageList[i-1][4]:
  67. return packageList[i-1][0]
  68. else:
  69. if packageList[i][4]:
  70. return packageList[i-1][0]
  71. else:
  72. return packageList[i][0]
  73. return packageList[end_index-1][0]
  74. '''
  75. if len(packageList)==0:
  76. return None,False
  77. list_legalPack = []
  78. for pack_index in range(len(packageList)):
  79. if DIRECT=="L" and (packageList[pack_index]["sentence_index"]>sentence_index or (packageList[pack_index]["sentence_index"]==sentence_index and packageList[pack_index]["offsetWords_begin"]>begin_index)):
  80. continue
  81. if DIRECT=="R" and (packageList[pack_index]["sentence_index"]<sentence_index or (packageList[pack_index]["sentence_index"]==sentence_index and packageList[pack_index]["offsetwords_begin"]<begin_index)):
  82. continue
  83. if (packageList[pack_index]["scope"][0][0]<sentence_index or (packageList[pack_index]["scope"][0][0]==sentence_index and packageList[pack_index]["scope"][0][1]<=begin_index)) and (packageList[pack_index]["scope"][1][0]>sentence_index or (packageList[pack_index]["scope"][1][0]==sentence_index and packageList[pack_index]["scope"][1][1]>=begin_index)):
  84. if MAX_DIS is not None:
  85. if abs(sentence_index-packageList[pack_index]["sentence_index"])<=MAX_DIS:
  86. list_legalPack.append(pack_index)
  87. else:
  88. list_legalPack.append(pack_index)
  89. # if (packageList[pack_index]["scope"][0][0] < sentence_index
  90. # or (packageList[pack_index]["scope"][0][0] == sentence_index
  91. # and packageList[pack_index]["scope"][0][1] <= begin_index))
  92. # and (packageList[pack_index]["scope"][1][0] > sentence_index
  93. # or (packageList[pack_index]["scope"][1][0] == sentence_index
  94. # and packageList[pack_index]["scope"][1][1] >= begin_index)):
  95. # pass
  96. _flag = True
  97. for _index in list_legalPack:
  98. if roleid in packageList[_index]["hit"]:
  99. continue
  100. else:
  101. _flag = False
  102. packageList[_index]["hit"].add(roleid)
  103. return packageList[_index]["pointer"],_flag
  104. if len(list_legalPack)>0:
  105. return packageList[0]["pointer"],_flag
  106. return None,False
  107. #生成合法的组合
  108. def get_legal_comba(list_entity,dict_role_combination):
  109. #拿到一个包中所有合法的组合
  110. def circle_package(_dict_legal_combination):
  111. list_dict_role_first = []
  112. for _role in _dict_legal_combination:
  113. if len(list_dict_role_first)==0:
  114. for _entity in _dict_legal_combination[_role]:
  115. if _entity !="":
  116. list_dict_role_first.append({_role:_entity})
  117. else:
  118. list_dict_role_after = []
  119. _find_count = 0
  120. for _entity in _dict_legal_combination[_role]:
  121. if _entity !="":
  122. for _dict in list_dict_role_first:
  123. _flag = True
  124. for _key1 in _dict:
  125. if _entity==_dict[_key1]:
  126. #修改为招标人和代理人可以为同一个
  127. if str(_key1) in ["0","1"] and str(_role) in ["0","1"]:
  128. _flag = True
  129. else:
  130. _flag = False
  131. if _flag:
  132. _find_count += 1
  133. _new_dict = copy.copy(_dict)
  134. _new_dict[_role] = _entity
  135. if len(list_dict_role_after)>100000:
  136. break
  137. list_dict_role_after.append(_new_dict)
  138. else:
  139. # 2021/5/25 update,同一实体(entity_text)不同角色
  140. if len(list_dict_role_after) > 100000:
  141. break
  142. for _dict in list_dict_role_first:
  143. for _key1 in _dict:
  144. if _entity == _dict[_key1]:
  145. _new_dict = copy.copy(_dict)
  146. _new_dict.pop(_key1)
  147. _new_dict[_role] = _entity
  148. list_dict_role_after.append({_role:_entity})
  149. if len(list_dict_role_after)==0:
  150. pass
  151. else:
  152. list_dict_role_first.extend(list_dict_role_after)
  153. return list_dict_role_first
  154. def recursive_package(_dict_legal_combination,set_legal_entity,dict_one_selution,list_all_selution):
  155. last_layer = False
  156. #若是空组合则放回空
  157. if len(_dict_legal_combination.keys())==0:
  158. return []
  159. #递归到最后一层则修改状态
  160. if len(_dict_legal_combination.keys())==1:
  161. last_layer = True
  162. #取一个角色开始进行遍历
  163. _key_role = list(_dict_legal_combination.keys())[0]
  164. for item in _dict_legal_combination[_key_role]:
  165. copy_dict_one_selution = copy.copy(dict_one_selution)
  166. copy_dict_legal_combination = {}
  167. copy_set_legal_entity = copy.copy(set_legal_entity)
  168. #复制余下的所有角色,进行下一轮递归
  169. for _key in _dict_legal_combination.keys():
  170. if _key!=_key_role:
  171. copy_dict_legal_combination[_key] = _dict_legal_combination[_key]
  172. #修改为招标人和代理人可以为同一个
  173. if item !="":
  174. _flag = True
  175. if str(_key_role) in ["0","1"]:
  176. for _key_flag in copy_dict_one_selution:
  177. if _key_flag not in ["0","1"] and copy_dict_one_selution[_key_flag]==item:
  178. _flag = False
  179. else:
  180. for _key_flag in copy_dict_one_selution:
  181. if copy_dict_one_selution[_key_flag]==item:
  182. _flag = False
  183. if _flag:
  184. copy_dict_one_selution[_key_role] = item
  185. '''
  186. if item not in copy_set_legal_entity:
  187. if item !="":
  188. copy_dict_one_selution[_key_role] = item
  189. '''
  190. copy_set_legal_entity.add(item)
  191. if last_layer:
  192. list_all_selution.append(copy_dict_one_selution)
  193. else:
  194. recursive_package(copy_dict_legal_combination,copy_set_legal_entity,copy_dict_one_selution,list_all_selution)
  195. #递归匹配各个包的结果
  196. def recursive_packages(_dict_legal_combination,dict_one_selution,list_all_selution):
  197. last_layer = False
  198. if len(_dict_legal_combination.keys())==0:
  199. return []
  200. if len(_dict_legal_combination.keys())==1:
  201. last_layer = True
  202. _key_pack = list(_dict_legal_combination.keys())[0]
  203. for item in _dict_legal_combination[_key_pack]:
  204. copy_dict_one_selution = copy.copy(dict_one_selution)
  205. copy_dict_legal_combination = {}
  206. for _key in _dict_legal_combination.keys():
  207. if _key!=_key_pack:
  208. copy_dict_legal_combination[_key] = _dict_legal_combination[_key]
  209. for _key_role in item.keys():
  210. copy_dict_one_selution[_key_pack+"$$"+_key_role] = item[_key_role]
  211. if last_layer:
  212. list_all_selution.append(copy_dict_one_selution)
  213. else:
  214. recursive_packages(copy_dict_legal_combination,copy_dict_one_selution,list_all_selution)
  215. return list_all_selution
  216. #循环获取所有包组合
  217. def circle_pageages(_dict_legal_combination):
  218. list_all_selution = []
  219. for _key_pack in _dict_legal_combination.keys():
  220. list_key_selution = []
  221. for item in _dict_legal_combination[_key_pack]:
  222. _dict = dict()
  223. for _key_role in item.keys():
  224. _dict[_key_pack+"$$"+_key_role] = item[_key_role]
  225. list_key_selution.append(_dict)
  226. if len(list_all_selution)==0:
  227. list_all_selution = list_key_selution
  228. else:
  229. _list_all_selution = []
  230. for item_1 in list_all_selution:
  231. for item_2 in list_key_selution:
  232. _list_all_selution.append(dict(item_1,**item_2))
  233. list_all_selution = _list_all_selution
  234. return list_all_selution
  235. #拿到各个包解析之后的结果
  236. _dict_legal_combination = {}
  237. for packageName in dict_role_combination.keys():
  238. _list_all_selution = []
  239. # recursive_package(dict_role_combination[packageName], set(), {}, _list_all_selution)
  240. _list_all_selution = circle_package(dict_role_combination[packageName])
  241. '''
  242. # print("===1")
  243. # print(packageName)
  244. for item in _list_all_selution:
  245. # print(item)
  246. # print("===2")
  247. '''
  248. #去除包含子集
  249. list_all_selution_simple = []
  250. _list_set_all_selution = []
  251. for item_selution in _list_all_selution:
  252. item_set_selution = set()
  253. for _key in item_selution.keys():
  254. item_set_selution.add((_key,item_selution[_key]))
  255. _list_set_all_selution.append(item_set_selution)
  256. if len(_list_set_all_selution)>1000:
  257. _dict_legal_combination[packageName] = _list_all_selution
  258. continue
  259. for i in range(len(_list_set_all_selution)):
  260. be_included = False
  261. for j in range(len(_list_set_all_selution)):
  262. if i!=j:
  263. if len(set(_list_set_all_selution[i])&set(_list_set_all_selution[j]))==len(_list_set_all_selution[i]) and len(_list_set_all_selution[i])!=len(_list_set_all_selution[j]):
  264. be_included = True
  265. if not be_included:
  266. list_all_selution_simple.append(_list_all_selution[i])
  267. _dict_legal_combination[packageName] = list_all_selution_simple
  268. _list_final_comba = []
  269. #对各个包的结果进行排列组合
  270. _comba_count = 1
  271. for _key in _dict_legal_combination.keys():
  272. _comba_count *= len(_dict_legal_combination[_key])
  273. #如果过大,则每个包只取概率最大的那个
  274. dict_pack_entity_prob = get_dict_entity_prob(list_entity)
  275. if _comba_count>250:
  276. new_dict_legal_combination = dict()
  277. for _key_pack in _dict_legal_combination.keys():
  278. MAX_PROB = -1000
  279. _MAX_PROB_COMBA = None
  280. for item in _dict_legal_combination[_key_pack]:
  281. # print(_key_pack,item)
  282. _dict = dict()
  283. for _key in item.keys():
  284. _dict[str(_key_pack)+"$$"+str(_key)] = item[_key]
  285. _prob = getSumExpectation(dict_pack_entity_prob, _dict)
  286. if _prob>MAX_PROB:
  287. MAX_PROB = _prob
  288. _MAX_PROB_COMBA = [item]
  289. if _MAX_PROB_COMBA is not None:
  290. new_dict_legal_combination[_key_pack] = _MAX_PROB_COMBA
  291. _dict_legal_combination = new_dict_legal_combination
  292. #recursive_packages(_dict_legal_combination, {}, _list_final_comba)
  293. _list_final_comba = circle_pageages(_dict_legal_combination)
  294. #除了Project包(招标人和代理人),其他包是不会有冲突的
  295. #查看是否有一个实体出现在了Project包和其他包中,如有,要进行裁剪
  296. _list_real_comba = []
  297. for dict_item in _list_final_comba:
  298. set_project = set()
  299. set_other = set()
  300. for _key in list(dict_item.keys()):
  301. if _key.split("$$")[0]=="Project":
  302. set_project.add(dict_item[_key])
  303. else:
  304. set_other.add(dict_item[_key])
  305. set_common = set_project&set_other
  306. if len(set_common)>0:
  307. dict_project = {}
  308. dict_not_project = {}
  309. for _key in list(dict_item.keys()):
  310. if dict_item[_key] in set_common:
  311. if str(_key.split("$$")[0])=="Project":
  312. dict_project[_key] = dict_item[_key]
  313. else:
  314. dict_not_project[_key] = dict_item[_key]
  315. else:
  316. dict_project[_key] = dict_item[_key]
  317. dict_not_project[_key] = dict_item[_key]
  318. _list_real_comba.append(dict_project)
  319. _list_real_comba.append(dict_not_project)
  320. else:
  321. _list_real_comba.append(dict_item)
  322. return _list_real_comba
  323. def get_dict_entity_prob(list_entity,on_value=0.5):
  324. dict_pack_entity_prob = {}
  325. for entity in list_entity:
  326. if entity.entity_type in ['org','company']:
  327. values = entity.values
  328. role_prob = float(values[int(entity.label)])
  329. _key = entity.packageName+"$$"+str(entity.label)
  330. if role_prob>=on_value and str(entity.label)!="5":
  331. _key_prob = _key+"$text$"+entity.entity_text
  332. if _key_prob in dict_pack_entity_prob:
  333. if role_prob>dict_pack_entity_prob[_key_prob][1]:
  334. dict_pack_entity_prob[_key_prob] = [entity.entity_text,role_prob]
  335. else:
  336. dict_pack_entity_prob[_key_prob] = [entity.entity_text,role_prob]
  337. return dict_pack_entity_prob
  338. #计算合计期望
  339. def getSumExpectation(dict_pack_entity_prob,combination,on_value=0.5):
  340. '''
  341. expect = 0
  342. for entity in list_entity:
  343. if entity.entity_type in ['org','company']:
  344. values = entity.values
  345. role_prob = float(values[int(entity.label)])
  346. _key = entity.packageName+"$$"+str(entity.label)
  347. if role_prob>on_value and str(entity.label)!="5":
  348. if _key in combination.keys() and combination[_key]==entity.entity_text:
  349. expect += math.pow(role_prob,4)
  350. else:
  351. expect -= math.pow(role_prob,4)
  352. '''
  353. #修改为同一个实体只取对应包-角色的最大的概率值
  354. expect = 0
  355. dict_entity_prob = {}
  356. for _key_pack_entity in dict_pack_entity_prob:
  357. _key_pack = _key_pack_entity.split("$text$")[0]
  358. role_prob = dict_pack_entity_prob[_key_pack_entity][1]
  359. if _key_pack in combination.keys() and combination[_key_pack]==dict_pack_entity_prob[_key_pack_entity][0]:
  360. if _key_pack_entity in dict_entity_prob.keys():
  361. if dict_entity_prob[_key_pack_entity]<role_prob:
  362. dict_entity_prob[_key_pack_entity] = role_prob
  363. else:
  364. dict_entity_prob[_key_pack_entity] = role_prob
  365. else:
  366. if _key_pack_entity in dict_entity_prob.keys():
  367. if dict_entity_prob[_key_pack_entity]>-role_prob:
  368. dict_entity_prob[_key_pack_entity] = -role_prob
  369. else:
  370. dict_entity_prob[_key_pack_entity] = -role_prob
  371. # for entity in list_entity:
  372. # if entity.entity_type in ['org','company']:
  373. # values = entity.values
  374. # role_prob = float(values[int(entity.label)])
  375. # _key = entity.packageName+"$$"+str(entity.label)
  376. # if role_prob>=on_value and str(entity.label)!="5":
  377. # if _key in combination.keys() and combination[_key]==entity.entity_text:
  378. # _key_prob = _key+entity.entity_text
  379. # if _key_prob in dict_entity_prob.keys():
  380. # if dict_entity_prob[_key_prob]<role_prob:
  381. # dict_entity_prob[_key_prob] = role_prob
  382. # else:
  383. # dict_entity_prob[_key_prob] = role_prob
  384. # else:
  385. # _key_prob = _key+entity.entity_text
  386. # if _key_prob in dict_entity_prob.keys():
  387. # if dict_entity_prob[_key_prob]>-role_prob:
  388. # dict_entity_prob[_key_prob] = -role_prob
  389. # else:
  390. # dict_entity_prob[_key_prob] = -role_prob
  391. for _key in dict_entity_prob.keys():
  392. symbol = 1 if dict_entity_prob[_key]>0 else -1
  393. expect += symbol*math.pow(dict_entity_prob[_key],2)
  394. return expect
  395. def getRoleList(list_sentence,list_entity,on_value = 0.5):
  396. '''
  397. @summary: 搜索树,得到所有不矛盾的角色组合,取合计期望值最大的作为结果返回
  398. @param:
  399. list_sentence:文章所有的sentence
  400. list_entity:文章所有的实体
  401. on_value:概率阈值
  402. @return:文章的角色list
  403. '''
  404. pack = getPackagesFromArticle(list_sentence,list_entity)
  405. if pack is None:
  406. return None
  407. PackageList,PackageSet,dict_PackageCode = pack
  408. #拿到所有可能的情况
  409. dict_role_combination = {}
  410. # print(PackageList)
  411. #拿到各个实体的packageName,packageCode
  412. for entity in list_entity:
  413. if entity.entity_type in ['org','company']:
  414. #过滤掉字数小于3个的实体
  415. if len(entity.entity_text)<=3:
  416. continue
  417. values = entity.values
  418. role_prob = float(values[int(entity.label)])
  419. if role_prob>=on_value and str(entity.label)!="5":
  420. if str(entity.label) in ["0","1"]:
  421. packageName = "Project"
  422. else:
  423. if len(PackageSet)>0:
  424. packagePointer,_ = getPackage(PackageList,entity.sentence_index,entity.begin_index,"role-"+str(entity.label))
  425. if packagePointer is None:
  426. #continue
  427. packageName = "Project"
  428. # print(entity.entity_text, packageName,entity.sentence_index,entity.begin_index)
  429. else:
  430. #add pointer_pack
  431. entity.pointer_pack = packagePointer
  432. packageName = packagePointer.entity_text
  433. # print(entity.entity_text, packageName)
  434. else:
  435. packageName = "Project"
  436. find_flag = False
  437. if packageName in dict_PackageCode.keys():
  438. packageCode = dict_PackageCode[packageName]
  439. else:
  440. packageCode = ""
  441. entity.packageCode = packageCode
  442. role_name = dict_role_id.get(str(entity.label))
  443. entity.roleName = role_name
  444. entity.packageName = packageName
  445. if entity.packageName in dict_role_combination.keys():
  446. if str(entity.label) in dict_role_combination[entity.packageName].keys():
  447. dict_role_combination[entity.packageName][str(entity.label)].add(entity.entity_text)
  448. else:
  449. dict_role_combination[entity.packageName][str(entity.label)] = set([entity.entity_text])
  450. else:
  451. dict_role_combination[entity.packageName] = {}
  452. #初始化空值
  453. roleIds = [0,1,2,3,4]
  454. for _roleId in roleIds:
  455. dict_role_combination[entity.packageName][str(_roleId)] = set([""])
  456. dict_role_combination[entity.packageName][str(entity.label)].add(entity.entity_text)
  457. list_real_comba = get_legal_comba(list_entity,dict_role_combination)
  458. # print("===role_combination",dict_role_combination)
  459. # print("== real_comba",list_real_comba)
  460. #拿到最大期望值的组合
  461. max_index = 0
  462. max_expect = -100
  463. _index = 0
  464. dict_pack_entity_prob = get_dict_entity_prob(list_entity)
  465. for item_combination in list_real_comba:
  466. expect = getSumExpectation(dict_pack_entity_prob, item_combination)
  467. if expect>max_expect:
  468. max_index = _index
  469. max_expect = expect
  470. _index += 1
  471. RoleList = []
  472. RoleSet = set()
  473. if len(list_real_comba)>0:
  474. for _key in list_real_comba[max_index].keys():
  475. packageName = _key.split("$$")[0]
  476. label = _key.split("$$")[1]
  477. role_name = dict_role_id.get(str(label))
  478. entity_text = list_real_comba[max_index][_key]
  479. if packageName in dict_PackageCode.keys():
  480. packagecode = dict_PackageCode.get(packageName)
  481. else:
  482. packagecode = ""
  483. RoleList.append(PREM(packageName,packagecode,role_name,entity_text,0,0,0.0,[]))
  484. RoleSet.add(entity_text)
  485. #根据最优树来修正list_entity中角色对包的连接
  486. for _entity in list_entity:
  487. if _entity.pointer_pack is not None:
  488. _pack_name = _entity.pointer_pack.entity_text
  489. _find_flag = False
  490. for _prem in RoleList:
  491. if _prem.packageName==_pack_name and _prem.entity_text==_entity.entity_text:
  492. _find_flag = True
  493. if not _find_flag:
  494. _entity.pointer_pack = None
  495. return RoleList,RoleSet,PackageList,PackageSet
  496. def getPackageScopePattern():
  497. '''
  498. @summary: 获取包的作用域关键词
  499. '''
  500. df = pd.read_excel(os.path.dirname(__file__)+"/end.xls")
  501. pattern = "("
  502. for item in df["list_word"]:
  503. item = str(item).replace("(","\(").replace(")","\)").replace(".","\.").replace("[","\[").replace("]","\]").replace("-","\-")
  504. pattern += item+"|"
  505. pattern = pattern[:-1]+")[::是为]|业绩.{,30}标段[0-9A-Za-z一二三四五六七八九十]{0,3}"
  506. return pattern
  507. pattern_packageScope = getPackageScopePattern()
  508. def getPackagesFromArticle(list_sentence,list_entity):
  509. '''
  510. @param:
  511. list_sentence:文章的句子list
  512. @summary: 将包的信息插入list_entity中
  513. @return: type:list if [包号,句子index,词偏移,标段号] meaning:文章的包/标段信息
  514. '''
  515. if len(list_sentence)==0:
  516. return None
  517. list_sentence.sort(key=lambda x:x.sentence_index)
  518. PackageList = []
  519. PackageList_scope = []
  520. PackageSet = set()
  521. dict_packageCode = dict()
  522. package_name_pattern = re.compile("((标[段号的包]|分包)的?(名[称单]?|包名))[::]?([^::]{3,30}?),{1}")
  523. package_N_name_pattern = re.compile("[^承](分?包|标段|标包|标|包|包组|子项目|包件|项目类型)编?号?[::]?[\((]?([0-9A-Za-z一二三四五六七八九十ⅠⅡⅢⅣⅤⅥⅦ]){1,2},{1}")
  524. package_number_pattern = re.compile("(([^承](包|标[段号的包]|分?包|包组|包件)编?号?|子项目|项目类型)[::]?[0-9A-Za-z一二三四五六七八九十ⅠⅡⅢⅣⅤⅥⅦ]{1,4}[^\.])[^至]?|([^\.]?第?[ⅠⅡⅢⅣⅤⅥⅦ0-9A-Za-z一二三四五六七八九十]{1,4}(包号|标[段号的包]|分?包))")
  525. # other_package_pattern = re.compile('(项目名称|物资名称|设备名称|场次名称|标段名称)[::](.{,20}?)(,|项目)') # 新正则识别标段
  526. other_package_pattern = re.compile('((项目|物资|设备|场次|标段|标的|产品)(名称))[::]([^,。]{2,50}?)[,。]') # # 2020/11/23 大网站规则 调整 package_N_name_pattern, package_N_name_pattern 中的项目 改为 子项目
  527. win_tenderer_pattern = re.compile('(中标人|供应商)[::](.{2,25})[,。]') # 2020/11/23 大网站规则 调整
  528. model_pattern = re.compile('(型号|序号)[::]([^,。]{2,20})[,。]') # 2020/11/23 大网站规则 调整
  529. number_pattern = re.compile("[0-9A-Za-z一二三四五六七八九十ⅠⅡⅢⅣⅤⅥⅦ]{1,4}")
  530. package_code_pattern = re.compile("(?:编号[::]?\s*)([-\dA-Za-z\(\)]+)")
  531. # 纯数字类型的包号统一,例如:'01','1'
  532. re_digital = re.compile("^\d+$")
  533. def changeIndexFromWordToWords(tokens,word_index):
  534. '''
  535. @summary:转换某个字的字偏移为词偏移
  536. '''
  537. before_index = 0
  538. after_index = 0
  539. for i in range(len(tokens)):
  540. after_index = after_index+len(tokens[i])
  541. if before_index<=word_index and after_index>=word_index:
  542. return i
  543. before_index = after_index
  544. package_names = []
  545. def extractPackageCode(tokens,word_index,size=20,pattern = package_code_pattern):
  546. '''
  547. @summary:抽取包附近的标段号
  548. @param:
  549. tokens:包所在句子的分词
  550. word_index:包所在字偏移
  551. size:左右各取多少个词
  552. pattern:提取标段号的正则
  553. @return: type:string,meaning:标段号
  554. '''
  555. index = changeIndexFromWordToWords(tokens,word_index)
  556. if index<size:
  557. begin = index
  558. else:
  559. begin = index-size
  560. if index+size>len(tokens):
  561. end = len(tokens)
  562. else:
  563. end = index+size
  564. #拿到左右两边的词语组成短语
  565. text = "".join(tokens[begin:end])
  566. #在短语中的字偏移
  567. new_word_index = word_index-len("".join(tokens[:begin]))
  568. min_distance = len(text)
  569. packageCode = None
  570. for the_iter in re.finditer(pattern,text):
  571. #算出最小距离
  572. distance = min([abs(new_word_index-the_iter.span()[0]),abs(new_word_index-the_iter.span()[1])])
  573. if distance<min_distance:
  574. min_distance = distance
  575. packageCode = the_iter.group(1)
  576. return packageCode
  577. #从标段介绍表格中提取包名和包号
  578. for i in range(len(list_sentence)):
  579. content = list_sentence[i].sentence_text
  580. names = re.findall(package_name_pattern,content)
  581. if names == []:
  582. names = re.findall(other_package_pattern, content)
  583. N_names = re.findall(package_N_name_pattern,content)
  584. if len(names)==1 and len(N_names)==1:
  585. package_names.append([names[0][-1],N_names[0][-1]])
  586. for i in range(len(list_sentence)):
  587. PackageList_item = []
  588. PackageList_item_scope = []
  589. content = list_sentence[i].sentence_text
  590. tokens = list_sentence[i].tokens
  591. _names = []
  592. # 2021/6/23 包名称去重
  593. for name in package_names:
  594. if name not in _names:
  595. _names.append(name)
  596. # for name in package_names[:20]:
  597. for name in _names[:20]:
  598. for index in findAllIndex(name[0],content):
  599. temp_package_number = re.findall(number_pattern,name[1])[0]
  600. if re.search(re_digital,temp_package_number):
  601. temp_package_number = str(int(temp_package_number))
  602. PackageList_item.append({"name":temp_package_number,"sentence_index":list_sentence[i].sentence_index,"offsetWords_begin":changeIndexFromWordToWords(tokens,index),"offsetWord_begin":index,"offsetWord_end":index+len(name[0])})
  603. # PackageList_item.append([temp_package_number,i,changeIndexFromWordToWords(tokens,index),index,index+len(str(temp_package_number))])
  604. code = extractPackageCode(tokens, index)
  605. if code is not None:
  606. dict_packageCode[temp_package_number] = code
  607. PackageSet.add(temp_package_number)
  608. for iter in re.finditer(package_number_pattern,content):
  609. temp_package_number = re.findall(number_pattern,content[iter.span()[0]:iter.span()[1]])[0]
  610. if re.search(re_digital, temp_package_number):
  611. temp_package_number = str(int(temp_package_number))
  612. PackageList_item.append({"name":temp_package_number,"sentence_index":list_sentence[i].sentence_index,"offsetWords_begin":changeIndexFromWordToWords(tokens,iter.span()[0]),"offsetWord_begin":iter.span()[0],"offsetWord_end":iter.span()[1]})
  613. # PackageList_item.append([temp_package_number,i,changeIndexFromWordToWords(tokens,iter.span()[0]),iter.span()[0],iter.span()[1]])
  614. code = extractPackageCode(tokens, iter.span()[0])
  615. if code is not None:
  616. dict_packageCode[temp_package_number] = code
  617. PackageSet.add(temp_package_number)
  618. #识别packageScope
  619. for iter in re.finditer(pattern_packageScope,content):
  620. PackageList_item_scope.append({"name":"","sentence_index":list_sentence[i].sentence_index,"offsetWords_begin":changeIndexFromWordToWords(tokens,iter.span()[0]),"offsetWord_begin":iter.span()[0],"offsetWord_end":iter.span()[1]})
  621. # PackageList_item_scope.append(["",i,changeIndexFromWordToWords(tokens,iter.span()[0]),iter.span()[0],iter.span()[1]])
  622. PackageList_item_scope = PackageList_item +PackageList_item_scope
  623. PackageList_item_scope.sort(key=lambda x:x["offsetWord_begin"])
  624. PackageList_scope = PackageList_scope+PackageList_item_scope
  625. PackageList_item.sort(key=lambda x:x["sentence_index"])
  626. #PackageList = PackageList+PackageList_item
  627. #不作为包
  628. # if len(PackageSet)==0:
  629. # for i in range(len(list_sentence)):
  630. # PackageList_item = []
  631. # PackageList_item_scope = []
  632. # content = list_sentence[i].sentence_text
  633. # tokens = list_sentence[i].tokens
  634. # for iter in re.finditer(other_package_pattern,content):
  635. # temp_package_number = iter.group(2)
  636. # PackageList_item.append({"name":temp_package_number,"sentence_index":list_sentence[i].sentence_index,"offsetWords_begin":changeIndexFromWordToWords(tokens,iter.span()[0]),"offsetWord_begin":iter.span()[0],"offsetWord_end":iter.span()[1]})
  637. # # PackageList_item.append([temp_package_number,i,changeIndexFromWordToWords(tokens,iter.span()[0]),iter.span()[0],iter.span()[1]])
  638. # code = extractPackageCode(tokens, iter.span()[0])
  639. # if code is not None:
  640. # dict_packageCode[temp_package_number] = code
  641. # PackageSet.add(temp_package_number)
  642. # #识别packageScope
  643. # for iter in re.finditer(pattern_packageScope,content):
  644. # PackageList_item_scope.append({"name":"","sentence_index":list_sentence[i].sentence_index,"offsetWords_begin":changeIndexFromWordToWords(tokens,iter.span()[0]),"offsetWord_begin":iter.span()[0],"offsetWord_end":iter.span()[1]})
  645. # # PackageList_item_scope.append(["",i,changeIndexFromWordToWords(tokens,iter.span()[0]),iter.span()[0],iter.span()[1]])
  646. # PackageList_item_scope = PackageList_item +PackageList_item_scope
  647. # PackageList_item_scope.sort(key=lambda x:x["offsetWord_begin"])
  648. # PackageList_scope = PackageList_scope+PackageList_item_scope
  649. # PackageList_item.sort(key=lambda x:x["sentence_index"])
  650. # 2020/11/23 大网站规则 调整
  651. if len(PackageSet)==0 and len(set([it.entity_text for it in list_entity if it.entity_type in ['org', 'company'] and it.label==2]))>1:
  652. for i in range(len(list_sentence)):
  653. PackageList_item = []
  654. PackageList_item_scope = []
  655. content = list_sentence[i].sentence_text
  656. tokens = list_sentence[i].tokens
  657. names = re.findall(other_package_pattern, content)
  658. N_names = re.findall(win_tenderer_pattern, content)
  659. if len(names) != 1 or len(N_names) != 1:
  660. continue
  661. for iter in re.finditer(other_package_pattern,content):
  662. temp_package_number = iter.group(4)
  663. xinghao = re.search(model_pattern, content)
  664. if xinghao:
  665. temp_package_number = temp_package_number + '+' + xinghao.group(2)
  666. # print('新正则采购包名补充',temp_package_number)
  667. if re.search(re_digital,temp_package_number):
  668. temp_package_number = str(int(temp_package_number))
  669. PackageList_item.append({"name":temp_package_number,"sentence_index":list_sentence[i].sentence_index,"offsetWords_begin":changeIndexFromWordToWords(tokens,iter.span()[0]),"offsetWord_begin":iter.span()[0],"offsetWord_end":iter.span()[1]})
  670. # PackageList_item.append([temp_package_number,i,changeIndexFromWordToWords(tokens,iter.span()[0]),iter.span()[0],iter.span()[1]])
  671. code = extractPackageCode(tokens, iter.span()[0])
  672. if code is not None:
  673. dict_packageCode[temp_package_number] = code
  674. PackageSet.add(temp_package_number)
  675. #识别packageScope
  676. for iter in re.finditer(pattern_packageScope,content):
  677. PackageList_item_scope.append({"name":"","sentence_index":list_sentence[i].sentence_index,"offsetWords_begin":changeIndexFromWordToWords(tokens,iter.span()[0]),"offsetWord_begin":iter.span()[0],"offsetWord_end":iter.span()[1]})
  678. # PackageList_item_scope.append(["",i,changeIndexFromWordToWords(tokens,iter.span()[0]),iter.span()[0],iter.span()[1]])
  679. PackageList_item_scope = PackageList_item +PackageList_item_scope
  680. PackageList_item_scope.sort(key=lambda x:x["offsetWord_begin"])
  681. PackageList_scope = PackageList_scope+PackageList_item_scope
  682. PackageList_item.sort(key=lambda x:x["sentence_index"])
  683. pattern_punctuation = "[::()\(\),,。;;]"
  684. # print("===packageList_scope",PackageList_scope)
  685. for i in range(len(list_sentence)):
  686. for j in range(len(PackageList_scope)):
  687. if i==PackageList_scope[j]["sentence_index"] and PackageList_scope[j]["name"]!="":
  688. _flag = False
  689. left_str = list_sentence[i].sentence_text[PackageList_scope[j]["offsetWord_begin"]-30:PackageList_scope[j]["offsetWord_begin"]+1]
  690. right_str = list_sentence[i].sentence_text[PackageList_scope[j]["offsetWord_begin"]:PackageList_scope[j]["offsetWord_begin"]+30]
  691. _left_find = re.findall(pattern_punctuation,left_str)
  692. _right_find = re.findall(pattern_punctuation,right_str)
  693. #print(left_str)
  694. if re.search("同",left_str[-1:]) is not None and PackageList_scope[j]["name"]=="一":
  695. continue
  696. if re.search("划分",right_str[:10]) is not None:
  697. continue
  698. if len(_left_find)>0 and _left_find[-1] in [":",":"]:
  699. _flag = True
  700. if len(_right_find)>0 and _right_find[0] in [":",":"]:
  701. _flag = True
  702. if _flag:
  703. scope_begin = [PackageList_scope[j]["sentence_index"],PackageList_scope[j]["offsetWords_begin"]]
  704. else:
  705. if j==0:
  706. scope_begin = [0,0]
  707. else:
  708. scope_begin = [PackageList_scope[j-1]["sentence_index"],PackageList_scope[j-1]["offsetWords_begin"]]
  709. if j==len(PackageList_scope)-1:
  710. scope_end = [list_sentence[-1].sentence_index,changeIndexFromWordToWords(list_sentence[-1].tokens, len(list_sentence[-1].sentence_text))]
  711. else:
  712. scope_end = [PackageList_scope[j+1]["sentence_index"],PackageList_scope[j+1]["offsetWords_begin"]]
  713. if PackageList_scope[j-1]["sentence_index"]==PackageList_scope[j]["sentence_index"] and PackageList_scope[j-1]["offsetWord_begin"]<=PackageList_scope[j]["offsetWord_begin"] and PackageList_scope[j-1]["offsetWord_end"]>=PackageList_scope[j]["offsetWord_end"]:
  714. continue
  715. #add package to entity
  716. _pack_entity = Entity(doc_id=list_sentence[0].doc_id,entity_id="%s_%s_%s_%s"%(list_sentence[0].doc_id,i,PackageList_scope[j]["offsetWord_begin"],PackageList_scope[j]["offsetWord_begin"]),entity_text=PackageList_scope[j]["name"],entity_type="package",sentence_index=PackageList_scope[j]["sentence_index"],begin_index=changeIndexFromWordToWords(list_sentence[i].tokens,PackageList_scope[j]["offsetWord_begin"]),end_index=changeIndexFromWordToWords(list_sentence[i].tokens,PackageList_scope[j]["offsetWord_end"]),wordOffset_begin=PackageList_scope[j]["offsetWord_begin"],wordOffset_end=PackageList_scope[j]["offsetWord_end"])
  717. list_entity.append(_pack_entity)
  718. copy_pack = copy.copy(PackageList_scope[j])
  719. copy_pack["scope"] = [scope_begin,scope_end]
  720. copy_pack["hit"] = set()
  721. copy_pack["pointer"] = _pack_entity
  722. PackageList.append(copy_pack)
  723. return PackageList,PackageSet,dict_packageCode
  724. from BiddingKG.dl.interface.modelFactory import Model_relation_extraction
  725. relationExtraction_model = Model_relation_extraction()
  726. def findAttributeAfterEntity(PackDict,roleSet,PackageList,PackageSet,list_entity,list_sentence,on_value = 0.5,on_value_person=0.5,sentence_len=4):
  727. '''
  728. @param:
  729. PackDict:文章包dict
  730. roleSet:文章所有角色的公司名称
  731. PackageList:文章的包信息
  732. PackageSet:文章所有包的名称
  733. list_entity:文章所有经过模型处理的实体
  734. on_value:金额模型的阈值
  735. on_value_person:联系人模型的阈值
  736. sentence_len:公司和属性间隔句子的最大长度
  737. @return:添加了属性信息的角色list
  738. '''
  739. #根据roleid添加金额到rolelist中
  740. def addMoneyByRoleid(packDict,packageName,roleid,money,money_prob):
  741. for i in range(len(packDict[packageName]["roleList"])):
  742. if packDict[packageName]["roleList"][i].role_name==dict_role_id.get(str(roleid)):
  743. if money_prob>packDict[packageName]["roleList"][i].money_prob:
  744. packDict[packageName]["roleList"][i].money = money
  745. packDict[packageName]["roleList"][i].money_prob = money_prob
  746. return packDict
  747. #根据实体名称添加金额到rolelist中
  748. def addMoneyByEntity(packDict,packageName,entity,money,money_prob):
  749. for i in range(len(packDict[packageName]["roleList"])):
  750. if packDict[packageName]["roleList"][i].entity_text==entity:
  751. # if money_prob>packDict[packageName]["roleList"][i].money_prob:
  752. # packDict[packageName]["roleList"][i].money = money
  753. # packDict[packageName]["roleList"][i].money_prob = money_prob
  754. if packDict[packageName]["roleList"][i].money_prob==0 : # 2021/7/20第一次更新金额
  755. packDict[packageName]["roleList"][i].money = money.entity_text
  756. packDict[packageName]["roleList"][i].money_prob = money_prob
  757. packDict[packageName]["roleList"][i].money_unit = money.money_unit
  758. elif money_prob>packDict[packageName]["roleList"][i].money_prob+0.2 or money.notes in ['大写']: # 2021/7/20改为优先选择大写金额,
  759. # print('已连接金额概率:money_prob:',packDict[packageName]["roleList"][i].money_prob)
  760. # print('链接金额备注 ',money.notes, money.entity_text, money.values)
  761. packDict[packageName]["roleList"][i].money = money.entity_text
  762. packDict[packageName]["roleList"][i].money_prob = money_prob
  763. packDict[packageName]["roleList"][i].money_unit = money.money_unit
  764. # print('链接中的金额:{0}, 单位:{1}'.format(money.entity_text, money.money_unit))
  765. return packDict
  766. #根据实体名称得到角色
  767. def getRoleWithText(packDict,entity_text):
  768. for pack in packDict.keys():
  769. for i in range(len(packDict[pack]["roleList"])):
  770. if packDict[pack]["roleList"][i].entity_text==entity_text:
  771. return packDict[pack]["roleList"][i].role_name
  772. def doesEntityOrLinkedEntity_inRoleSet(entity,RoleSet):
  773. _list_entitys = [entity]+entity.linked_entitys
  774. for _entity in _list_entitys:
  775. if _entity.entity_text in RoleSet:
  776. return True
  777. p_entity = 0
  778. # 2021/7/19 顺序比较金额,前面是后面的一万倍则把前面金额/10000
  779. money_list = [it for it in list_entity if it.entity_type=="money"]
  780. for i in range(len(money_list)-1):
  781. for j in range(1, len(money_list)):
  782. if (float(money_list[i].entity_text) > 5000000000 or money_list[j].notes=='大写') and \
  783. Decimal(money_list[i].entity_text)/Decimal(money_list[j].entity_text)==10000:
  784. money_list[i].entity_text = str(Decimal(money_list[i].entity_text)/10000)
  785. # print('连接前修改大于50亿金额:前面是后面的一万倍则把前面金额/10000')
  786. #遍历所有实体
  787. while(p_entity<len(list_entity)):
  788. entity = list_entity[p_entity]
  789. '''
  790. #招标金额从后往前找
  791. if entity.entity_type=="money":
  792. if entity.values[entity.label]>=on_value:
  793. if str(entity.label)=="0":
  794. packagePointer,_ = getPackage(PackageList,entity.sentence_index,entity.begin_index,"money-"+str(entity.label))
  795. if packagePointer is None:
  796. packageName = "Project"
  797. else:
  798. packageName = packagePointer.entity_text
  799. addMoneyByRoleid(PackDict, packageName, "0", entity.entity_text, entity.values[entity.label])
  800. '''
  801. ''' # 2020/11/25 与下面的联系人连接步骤重复,取消
  802. if entity.entity_type=="person":
  803. if entity.values[entity.label]>=on_value_person:
  804. if str(entity.label)=="1":
  805. for i in range(len(PackDict["Project"]["roleList"])):
  806. if PackDict["Project"]["roleList"][i].role_name=="tenderee":
  807. PackDict["Project"]["roleList"][i].linklist.append((entity.entity_text,entity.person_phone))
  808. # add pointer_person
  809. for _entity in list_entity:
  810. if dict_role_id.get(str(_entity.label))=="tenderee":
  811. for i in range(len(PackDict["Project"]["roleList"])):
  812. if PackDict["Project"]["roleList"][i].entity_text==_entity.entity_text and PackDict["Project"]["roleList"][i].role_name=="tenderee":
  813. _entity.pointer_person = entity
  814. elif str(entity.label)=="2":
  815. for i in range(len(PackDict["Project"]["roleList"])):
  816. if PackDict["Project"]["roleList"][i].role_name=="agency":
  817. PackDict["Project"]["roleList"][i].linklist.append((entity.entity_text,entity.person_phone))
  818. # add pointer_person
  819. for _entity in list_entity:
  820. if dict_role_id.get(str(_entity.label))=="agency":
  821. for i in range(len(PackDict["Project"]["roleList"])):
  822. if PackDict["Project"]["roleList"][i].entity_text==_entity.entity_text and PackDict["Project"]["roleList"][i].role_name=="agency":
  823. _entity.pointer_person = entity
  824. '''
  825. # #金额往前找实体
  826. # if entity.entity_type=="money":
  827. # if entity.values[entity.label]>=on_value:
  828. # p_entity_money= p_entity
  829. # entity_money = list_entity[p_entity_money]
  830. # if len(PackageSet)>0:
  831. # packagePointer,_ = getPackage(PackageList,entity_money.sentence_index,entity_money.begin_index,"money-"+str(entity_money.entity_text)+"-"+str(entity_money.label))
  832. # if packagePointer is None:
  833. # packageName_entity = "Project"
  834. # else:
  835. # packageName_entity = packagePointer.entity_text
  836. # else:
  837. # packageName_entity = "Project"
  838. # while(p_entity_money>0):
  839. # entity_before = list_entity[p_entity_money]
  840. # if entity_before.entity_type in ['org','company']:
  841. # if str(entity_before.label)=="1":
  842. # addMoneyByEntity(PackDict, packageName_entity, entity_before.entity_text, entity_money.entity_text, entity_money.values[entity_money.label])
  843. # #add pointer_money
  844. # entity_before.pointer_money = entity_money
  845. # break
  846. # p_entity_money -= 1
  847. #如果实体属于角色集合,则往后找属性
  848. if doesEntityOrLinkedEntity_inRoleSet(entity, roleSet):
  849. p_entity += 1
  850. #循环查找符合的属性
  851. while(p_entity<len(list_entity)):
  852. entity_after = list_entity[p_entity]
  853. if entity_after.sentence_index-entity.sentence_index>=sentence_len:
  854. p_entity -= 1
  855. break
  856. #若是遇到公司实体,则跳出循环
  857. if entity_after.entity_type in ['org','company']:
  858. p_entity -= 1
  859. break
  860. if entity_after.values is not None:
  861. if entity_after.entity_type=="money":
  862. if entity_after.values[entity_after.label]>=on_value:
  863. '''
  864. #招标金额从后往前找
  865. if str(entity_after.label)=="0":
  866. packagePointer,_ = getPackage(PackageList,entity.sentence_index,entity.begin_index,"money-"+str(entity.label))
  867. if packagePointer is None:
  868. packageName = "Project"
  869. else:
  870. packageName = packagePointer.entity_text
  871. addMoneyByRoleid(PackDict, packageName, "0", entity_after.entity_text, entity_after.values[entity_after.label])
  872. '''
  873. if str(entity_after.label)=="1":
  874. #print(entity_after.entity_text,entity.entity_text)
  875. _list_entitys = [entity]+entity.linked_entitys
  876. if len(PackageSet)>0:
  877. packagePointer,_ = getPackage(PackageList,entity_after.sentence_index,entity_after.begin_index,"money-"+str(entity_after.entity_text)+"-"+str(entity_after.label))
  878. if packagePointer is None:
  879. packageName_entity = "Project"
  880. else:
  881. packageName_entity = packagePointer.entity_text
  882. else:
  883. packageName_entity = "Project"
  884. if str(entity.label) in ["2","3","4"]:
  885. # addMoneyByEntity(PackDict, packageName_entity, entity.entity_text, entity_after.entity_text, entity_after.values[entity_after.label])
  886. if entity_after.notes == '单价' or float(entity_after.entity_text)<5000: #2021/12/17 调整小金额阈值,避免203608823.html 两次金额一次万元没提取到的情况
  887. addMoneyByEntity(PackDict, packageName_entity, entity.entity_text, entity_after,
  888. 0.5)
  889. entity.pointer_money = entity_after
  890. # print('role zhao money', entity.entity_text, '中标金额:', entity_after.entity_text)
  891. else:
  892. addMoneyByEntity(PackDict, packageName_entity, entity.entity_text, entity_after,
  893. entity_after.values[entity_after.label])
  894. entity.pointer_money = entity_after
  895. # print('role zhao money', entity.entity_text, '中标金额:', entity_after.entity_text)
  896. if entity_after.values[entity_after.label]>0.6:
  897. break # 2021/7/16 新增,找到中标金额,非单价即停止,不再往后找金额
  898. #add pointer_money
  899. # entity.pointer_money = entity_after
  900. # print('role zhao money', entity.entity_text, '中标金额:', entity_after.entity_text)
  901. # if entity_after.notes!='单价':
  902. # break # 2021/7/16 新增,找到中标金额即停止,不再往后找金额
  903. '''
  904. if entity_after.entity_type=="person":
  905. if entity_after.values[entity_after.label]>=on_value_person:
  906. if str(entity_after.label)=="1":
  907. for i in range(len(roleList)):
  908. if roleList[i].role_name=="tenderee":
  909. roleList[i].linklist.append((entity_after.entity_text,entity_after.person_phone))
  910. elif str(entity_after.label)=="2":
  911. for i in range(len(roleList)):
  912. if roleList[i].role_name=="agency":
  913. roleList[i].linklist.append((entity_after.entity_text,entity_after.person_phone))
  914. elif str(entity_after.label)=="3":
  915. _list_entitys = [entity]+entity.linked_entitys
  916. for _entity in _list_entitys:
  917. for i in range(len(roleList)):
  918. if roleList[i].entity_text==_entity.entity_text:
  919. if entity_after.sentence_index-_entity.sentence_index>1 and len(roleList[i].linklist)>0:
  920. break
  921. roleList[i].linklist.append((entity_after.entity_text,entity_after.person_phone))
  922. '''
  923. p_entity += 1
  924. p_entity += 1
  925. ''''''
  926. # 通过模型分类的招标/代理联系人
  927. list_sentence = sorted(list_sentence, key=lambda x: x.sentence_index)
  928. person_list = [entity for entity in list_entity if entity.entity_type == 'person' and entity.label in [1, 2]]
  929. tenderee_contact = set()
  930. tenderee_phone = set()
  931. agency_contact = set()
  932. agency_phone = set()
  933. winter_contact = set()
  934. for _person in person_list:
  935. if _person.label == 1:
  936. tenderee_contact.add(_person.entity_text)
  937. if _person.label == 2:
  938. agency_contact.add(_person.entity_text)
  939. # 正则匹配无 '主体/联系人' 的电话
  940. # 例:"采购人联系方式:0833-5226788,"
  941. phone_pattern = '(1[3|4|5|6|7|8|9][0-9][-—-―]?\d{4}[-—-―]?\d{4}|' \
  942. '\+86.?1[3|4|5|6|7|8|9]\d{9}|' \
  943. '0[1-9]\d{1,2}[-—-―][1-9]\d{6,7}/[1-9]\d{6,10}|' \
  944. '0[1-9]\d{1,2}[-—-―]\d{7,8}.?转\d{1,4}|' \
  945. '0[1-9]\d{1,2}[-—-―]\d{7,8}[-—-―]\d{1,4}|' \
  946. '0[1-9]\d{1,2}[-—-―]?[1-9]\d{6}\d?(?=1[3|4|5|6|7|8|9]\d{9})|' \
  947. '0[1-9]\d{1,2}[-—-―]?[1-9]\d{6}\d?(?=0[1-9]\d{1,2}[-—-―]?[1-9]\d{6}\d?)|' \
  948. '0[1-9]\d{1,2}[-—-―]?[1-9]\d{6}\d?(?=[1-9]\d{6,7})|' \
  949. '0[1-9]\d{1,2}[-—-―]?[1-9]\d{6}\d?|' \
  950. '[\(|\(]0[1-9]\d{1,2}[\)|\)]-?\d{7,8}-?\d{,4}|' \
  951. '[2-9]\d{6,7})'
  952. re_tenderee_phone = re.compile(
  953. "(?:(?:(?:采购|招标|议价|议标|比选)(?:人|公司|单位|组织|部门)|建设(?:单位|业主)|(?:采购|招标|甲)方|询价单位|项目业主|业主)[^。]{0,5}(?:电话|联系方式|联系人)[::]?[^。]{0,7}?)"
  954. # 电话号码
  955. + phone_pattern)
  956. # 例:"采购人地址和联系方式:峨边彝族自治县教育局,0833-5226788,"
  957. re_tenderee_phone2 = re.compile(
  958. "(?:(?:(?:采购|招标|议价|议标|比选)(?:人|公司|单位|组织|部门)|建设(?:单位|业主)|(?:采购|招标|甲)方|询价单位|项目业主|业主)[^。]{0,3}(?:地址)[^。]{0,3}(?:电话|联系方式|联系人)[::]?[^。]{0,20}?)"
  959. # 电话号码
  960. + phone_pattern)
  961. re_agent_phone = re.compile(
  962. "(?:(?:代理(?:人|机构|公司|单位|组织|方)|采购机构|集中采购机构|集采机构|招标机构)[^。]{0,5}(?:电话|联系方式|联系人)[::]?[^。]{0,7}?)"
  963. # 电话号码
  964. + phone_pattern)
  965. re_agent_phone2 = re.compile(
  966. "(?:(?:代理(?:人|机构|公司|单位|组织|方)|采购机构|集中采购机构|集采机构|招标机构)[^。]{0,3}(?:地址)[^。]{0,3}(?:电话|联系方式|联系人)[::]?[^。]{0,20}?)"
  967. # 电话号码
  968. + phone_pattern)
  969. content = ""
  970. for _sentence in list_sentence:
  971. content += "".join(_sentence.tokens)
  972. _content = copy.deepcopy(content)
  973. while re.search("(.)(,)([^0-9])|([^0-9])(,)(.)", content):
  974. content_words = list(content)
  975. for i in re.finditer("(.)(,)([^0-9])", content):
  976. content_words[i.span(2)[0]] = ""
  977. for i in re.finditer("([^0-9])(,)(.)", content):
  978. content_words[i.span(2)[0]] = ""
  979. content = "".join(content_words)
  980. content = re.sub("[::]|[\((]|[\))]", "", content)
  981. _tenderee_phone = re.findall(re_tenderee_phone, content)
  982. # 更新正则确定的角色属性
  983. for i in range(len(PackDict["Project"]["roleList"])):
  984. if PackDict["Project"]["roleList"][i].role_name == "tenderee":
  985. _tenderee_phone = re.findall(re_tenderee_phone, content)
  986. if _tenderee_phone:
  987. for _phone in _tenderee_phone:
  988. _phone = _phone.split("/") # 分割多个号码
  989. for one_phone in _phone:
  990. PackDict["Project"]["roleList"][i].linklist.append(("", one_phone))
  991. tenderee_phone.add(one_phone)
  992. _tenderee_phone2 = re.findall(re_tenderee_phone2, content)
  993. if _tenderee_phone2:
  994. for _phone in _tenderee_phone2:
  995. _phone = _phone.split("/")
  996. for one_phone in _phone:
  997. PackDict["Project"]["roleList"][i].linklist.append(("", one_phone))
  998. tenderee_phone.add(one_phone)
  999. if PackDict["Project"]["roleList"][i].role_name == "agency":
  1000. _agent_phone = re.findall(re_agent_phone, content)
  1001. if _agent_phone:
  1002. for _phone in _agent_phone:
  1003. _phone = _phone.split("/")
  1004. for one_phone in _phone:
  1005. PackDict["Project"]["roleList"][i].linklist.append(("", one_phone))
  1006. agency_phone.add(one_phone)
  1007. _agent_phone2 = re.findall(re_agent_phone2, content)
  1008. if _agent_phone2:
  1009. for _phone in _agent_phone2:
  1010. _phone = _phone.split("/")
  1011. for one_phone in _phone:
  1012. PackDict["Project"]["roleList"][i].linklist.append(("", one_phone))
  1013. agency_phone.add(one_phone)
  1014. # km配对方法
  1015. def dispatch(match_list):
  1016. main_roles = list(set([match.main_role for match in match_list]))
  1017. attributes = list(set([match.attribute for match in match_list]))
  1018. label = np.zeros(shape=(len(main_roles), len(attributes)))
  1019. for match in match_list:
  1020. main_role = match.main_role
  1021. attribute = match.attribute
  1022. value = match.value
  1023. label[main_roles.index(main_role), attributes.index(attribute)] = value + 10000
  1024. # print(label)
  1025. gragh = -label
  1026. # km算法
  1027. row, col = linear_sum_assignment(gragh)
  1028. max_dispatch = [(i, j) for i, j, value in zip(row, col, gragh[row, col]) if value]
  1029. # return [Match(main_roles[row], attributes[col]) for row, col in max_dispatch]
  1030. return [(main_roles[row], attributes[col]) for row, col in max_dispatch]
  1031. # 正则提取电话号码实体
  1032. # key_word = re.compile('((?:电话|联系方式|联系人).{0,4}?)([0-1]\d{6,11})')
  1033. phone = re.compile('1[3|4|5|6|7|8|9][0-9][-—-―]?\d{4}[-—-―]?\d{4}|'
  1034. '\+86.?1[3|4|5|6|7|8|9]\d{9}|'
  1035. # '0[^0]\d{1,2}[-—-―][1-9]\d{6,7}/[1-9]\d{6,10}|'
  1036. '0[1-9]\d{1,2}[-—-―]\d{7,8}.?转\d{1,4}|'
  1037. '0[1-9]\d{1,2}[-—-―]\d{7,8}[-—-―]\d{1,4}|'
  1038. '0[1-9]\d{1,2}[-—-―]?[1-9]\d{6}\d?(?=1[3|4|5|6|7|8|9]\d{9})|'
  1039. '0[1-9]\d{1,2}[-—-―]?[1-9]\d{6}\d?(?=0[1-9]\d{1,2}[-—-―]?[1-9]\d{6}\d?)|'
  1040. '0[1-9]\d{1,2}[-—-―]?[1-9]\d{6}\d?(?=[1-9]\d{6,7})|'
  1041. '0[1-9]\d{1,2}[-—-―]?[1-9]\d{6}\d?|'
  1042. '[\(|\(]0[1-9]\d{1,2}[\)|\)]-?\d{7,8}-?\d{,4}|'
  1043. '[2-9]\d{6,7}')
  1044. phone_entitys = []
  1045. for _sentence in list_sentence:
  1046. sentence_text = _sentence.sentence_text
  1047. list_tokenbegin = []
  1048. begin = 0
  1049. for i in range(0, len(_sentence.tokens)):
  1050. list_tokenbegin.append(begin)
  1051. begin += len(str(_sentence.tokens[i]))
  1052. list_tokenbegin.append(begin + 1)
  1053. res_set = set()
  1054. for i in re.finditer(phone, sentence_text):
  1055. res_set.add((i.group(), i.start(), i.end()))
  1056. res_set = sorted(list(res_set),key=lambda x:x[1])
  1057. last_phone_mask = True
  1058. for item_idx in range(len(res_set)):
  1059. item = res_set[item_idx]
  1060. phone_left = sentence_text[max(0, item[1] - 10):item[1]]
  1061. phone_right = sentence_text[item[2]:item[2] + 8]
  1062. # 排除“传真号”和其它错误项
  1063. if re.search("传,?真|信,?箱|邮,?[箱件]", phone_left):
  1064. if not re.search("电,?话", phone_left):
  1065. last_phone_mask = False
  1066. continue
  1067. if re.search("注册[证号]|帐,?号|编,?[号码]|报,?价|证,?号|价,?格|[\(\(]万?元[\)\)]|[a-zA-Z]+\d*$", phone_left):
  1068. last_phone_mask = False
  1069. continue
  1070. if re.search("^\d{0,4}[.,]\d{2,}|^[0-9a-zA-Z\.]*@|^\d*[a-zA-Z]+", phone_right):
  1071. last_phone_mask = False
  1072. continue
  1073. # if:上一个phone实体不符合条件
  1074. if not last_phone_mask:
  1075. item_start = item[1]
  1076. last_item_end = res_set[item_idx-1][2]
  1077. if item_start - last_item_end<=1 or re.search("^\d+$",sentence_text[last_item_end:item_start]):
  1078. last_phone_mask = False
  1079. continue
  1080. for j in range(len(list_tokenbegin)):
  1081. if list_tokenbegin[j] == item[1]:
  1082. begin_index = j
  1083. break
  1084. elif list_tokenbegin[j] > item[1]:
  1085. begin_index = j - 1
  1086. break
  1087. for j in range(begin_index, len(list_tokenbegin)):
  1088. if list_tokenbegin[j] >= item[2]:
  1089. end_index = j - 1
  1090. break
  1091. _entity = Entity(_sentence.doc_id, None, item[0], "phone", _sentence.sentence_index, begin_index, end_index, item[1],
  1092. item[2])
  1093. phone_entitys.append(_entity)
  1094. last_phone_mask = True
  1095. def is_company(entity,text):
  1096. # 判断"公司"实体是否为地址地点
  1097. if entity.label!=5 and entity.values[entity.label]>0.5:
  1098. return True
  1099. if ent.is_tail==True:
  1100. return False
  1101. entity_left = text[max(0,entity.wordOffset_begin-10):entity.wordOffset_begin]
  1102. entity_left = re.sub(",()\(\)::","",entity_left)
  1103. entity_left = entity_left[-5:]
  1104. if re.search("地址|地点|银行[::]",entity_left):
  1105. return False
  1106. else:
  1107. return True
  1108. pre_entity = []
  1109. for ent in list_entity:
  1110. 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]) \
  1111. or (ent.entity_type=='location' and len(ent.entity_text)>5):
  1112. pre_entity.append(ent)
  1113. text_data,pre_data = relationExtraction_model.encode(pre_entity + phone_entitys, list_sentence)
  1114. # print(pre_data)
  1115. maxlen = 512
  1116. relation_list = []
  1117. if 0<len(text_data)<=maxlen:
  1118. relation_list = relationExtraction_model.predict(text_data, pre_data)
  1119. else:
  1120. # 公告大于maxlen时,分段预测
  1121. start = 0
  1122. while start<len(pre_data):
  1123. _pre_data = pre_data[start:start+maxlen]
  1124. _text_data = text_data[start:start+maxlen]
  1125. relation_list.extend(relationExtraction_model.predict(_text_data,_pre_data))
  1126. start = start + maxlen - 120
  1127. # 去重结果
  1128. relation_list = list(set(relation_list))
  1129. # print(relation_list)
  1130. tokens_num_dict = dict()
  1131. last_tokens_num = 0
  1132. for sentence in list_sentence:
  1133. _index = sentence.sentence_index
  1134. if _index == 0:
  1135. tokens_num_dict[_index] = 0
  1136. else:
  1137. tokens_num_dict[_index] = tokens_num_dict[_index - 1] + last_tokens_num
  1138. last_tokens_num = len(sentence.tokens)
  1139. right_combination = [('org','person'),('company','person'),('company','location'),('org','location'),('person','phone')]
  1140. linked_company = set()
  1141. linked_person = set()
  1142. for predicate in ["rel_address","rel_phone","rel_person"]:
  1143. _match_list = []
  1144. _match_combo = []
  1145. for relation in relation_list:
  1146. _subject = relation[0]
  1147. _object = relation[2]
  1148. if isinstance(_subject,Entity) and isinstance(_object,Entity) and (_subject.entity_type,_object.entity_type) in right_combination:
  1149. if relation[1]==predicate:
  1150. if predicate=="rel_person":
  1151. if (_subject.label==0 and _object.entity_text in agency_contact ) or (_subject.label==1 and _object.entity_text in tenderee_contact):
  1152. continue
  1153. distance = (tokens_num_dict[_object.sentence_index] + _object.begin_index) - (
  1154. tokens_num_dict[_subject.sentence_index] + _subject.end_index)
  1155. if distance>0:
  1156. value = (-1 / 2 * (distance ** 2))/10000
  1157. else:
  1158. distance = abs(distance)
  1159. value = (-1 / 2 * (distance ** 2))
  1160. _match_list.append(Match(_subject,_object,value))
  1161. _match_combo.append((_subject,_object))
  1162. match_result = dispatch(_match_list)
  1163. error_list = []
  1164. for mat in list(set(_match_combo)-set(match_result)):
  1165. for temp in match_result:
  1166. if mat[1]==temp[1] and mat[0]!=temp[0]:
  1167. error_list.append(mat)
  1168. break
  1169. result = list(set(_match_combo)-set(error_list))
  1170. if predicate=='rel_person':
  1171. # 从后往前更新状态,已近后向链接的属性不在前向链接(解决错误链接)
  1172. result = sorted(result,key=lambda x:x[1].begin_index,reverse=True)
  1173. for combo in result:
  1174. is_continue = False
  1175. if not combo[0].pointer_person:
  1176. combo[0].pointer_person = []
  1177. if combo[1].begin_index<combo[0].begin_index:
  1178. if combo[0].pointer_person:
  1179. for temp in combo[0].pointer_person:
  1180. if temp.begin_index>combo[0].begin_index:
  1181. is_continue = True
  1182. break
  1183. if is_continue: continue
  1184. combo[0].pointer_person.append(combo[1])
  1185. linked_company.add(combo[0])
  1186. linked_person.add(combo[1])
  1187. # print(1,combo[0].entity_text,combo[1].entity_text)
  1188. if predicate=='rel_address':
  1189. result = sorted(result,key=lambda x:x[1].begin_index,reverse=True)
  1190. for combo in result:
  1191. if combo[0].pointer_address:
  1192. continue
  1193. combo[0].pointer_address = combo[1]
  1194. # print(2,combo[0].entity_text,combo[1].entity_text)
  1195. if predicate=='rel_phone':
  1196. result = sorted(result,key=lambda x:x[1].begin_index,reverse=True)
  1197. for combo in result:
  1198. is_continue = False
  1199. if not combo[0].person_phone:
  1200. combo[0].person_phone = []
  1201. if combo[1].begin_index<combo[0].begin_index:
  1202. if combo[0].person_phone:
  1203. for temp in combo[0].person_phone:
  1204. if temp.begin_index>combo[0].begin_index:
  1205. is_continue = True
  1206. break
  1207. if is_continue: continue
  1208. combo[0].person_phone.append(combo[1])
  1209. if combo[0].label in [1,2]:
  1210. if PackDict.get("Project"):
  1211. for i in range(len(PackDict["Project"]["roleList"])):
  1212. if (combo[0].label==1 and PackDict["Project"]["roleList"][i].role_name=='tenderee') \
  1213. or (combo[0].label==2 and PackDict["Project"]["roleList"][i].role_name=='agency'):
  1214. PackDict["Project"]["roleList"][i].linklist.append((combo[0].entity_text,combo[1].entity_text))
  1215. break
  1216. # print(3,combo[0].entity_text,combo[1].entity_text)
  1217. # 更新 PackDict
  1218. not_sure_linked = []
  1219. for link_p in list(linked_company):
  1220. for k in PackDict.keys():
  1221. for i in range(len(PackDict[k]["roleList"])):
  1222. if PackDict[k]["roleList"][i].role_name == "tenderee":
  1223. if PackDict[k]["roleList"][i].entity_text != link_p.entity_text and link_p.label == 0:
  1224. not_sure_linked.append(link_p)
  1225. continue
  1226. if PackDict[k]["roleList"][i].entity_text == link_p.entity_text:
  1227. for per in link_p.pointer_person:
  1228. person_phone = [phone for phone in per.person_phone] if per.person_phone else []
  1229. if not person_phone:
  1230. if per.entity_text not in agency_contact:
  1231. PackDict[k]["roleList"][i].linklist.append((per.entity_text, ""))
  1232. continue
  1233. for _p in person_phone:
  1234. if per.entity_text not in agency_contact and _p.entity_text not in agency_phone:
  1235. PackDict[k]["roleList"][i].linklist.append((per.entity_text, _p.entity_text))
  1236. elif PackDict[k]["roleList"][i].role_name == "agency":
  1237. if PackDict[k]["roleList"][i].entity_text != link_p.entity_text and link_p.label == 1:
  1238. not_sure_linked.append(link_p)
  1239. continue
  1240. if PackDict[k]["roleList"][i].entity_text == link_p.entity_text:
  1241. for per in link_p.pointer_person:
  1242. person_phone = [phone for phone in per.person_phone] if per.person_phone else []
  1243. if not person_phone:
  1244. if per.entity_text not in tenderee_contact:
  1245. PackDict[k]["roleList"][i].linklist.append((per.entity_text, ""))
  1246. continue
  1247. for _p in person_phone:
  1248. if per.entity_text not in tenderee_contact and _p.entity_text not in tenderee_phone:
  1249. PackDict[k]["roleList"][i].linklist.append((per.entity_text, _p.entity_text))
  1250. else:
  1251. if PackDict[k]["roleList"][i].entity_text == link_p.entity_text:
  1252. for per in link_p.pointer_person:
  1253. person_phone = [phone for phone in per.person_phone] if per.person_phone else []
  1254. if not person_phone:
  1255. if per.entity_text not in tenderee_contact and per.entity_text not in agency_contact:
  1256. PackDict[k]["roleList"][i].linklist.append((per.entity_text, ""))
  1257. winter_contact.add(per.entity_text)
  1258. continue
  1259. for _p in person_phone:
  1260. if per.entity_text not in tenderee_contact and _p.entity_text not in tenderee_phone and \
  1261. per.entity_text not in agency_contact and _p.entity_text not in agency_phone:
  1262. PackDict[k]["roleList"][i].linklist.append((per.entity_text, _p.entity_text))
  1263. winter_contact.add(per.entity_text)
  1264. # 更新org/company实体label为0,1的链接
  1265. for link_p in not_sure_linked:
  1266. for k in PackDict.keys():
  1267. for i in range(len(PackDict[k]["roleList"])):
  1268. if PackDict[k]["roleList"][i].role_name == "tenderee":
  1269. if link_p.label == 0:
  1270. for per in link_p.pointer_person:
  1271. person_phone = [phone for phone in per.person_phone] if per.person_phone else []
  1272. if not person_phone:
  1273. if per.entity_text not in agency_contact and per.entity_text not in winter_contact:
  1274. PackDict[k]["roleList"][i].linklist.append((per.entity_text, ""))
  1275. continue
  1276. for _p in person_phone:
  1277. if per.entity_text not in agency_contact and _p.entity_text not in agency_phone and per.entity_text not in winter_contact:
  1278. PackDict[k]["roleList"][i].linklist.append((per.entity_text, _p.entity_text))
  1279. elif PackDict[k]["roleList"][i].role_name == "agency":
  1280. if link_p.label == 1:
  1281. for per in link_p.pointer_person:
  1282. person_phone = [phone for phone in per.person_phone] if per.person_phone else []
  1283. if not person_phone:
  1284. if per.entity_text not in tenderee_contact and per.entity_text not in winter_contact:
  1285. PackDict[k]["roleList"][i].linklist.append((per.entity_text, ""))
  1286. continue
  1287. for _p in person_phone:
  1288. if per.entity_text not in tenderee_contact and _p.entity_text not in tenderee_phone and per.entity_text not in winter_contact:
  1289. PackDict[k]["roleList"][i].linklist.append((per.entity_text, _p.entity_text))
  1290. re_split = re.compile("[^\u4e00-\u9fa5、](十一|十二|十三|十四|十五|一|二|三|四|五|六|七|八|九|十)、")
  1291. split_list = [0] * 16
  1292. split_dict = {
  1293. "一、": 1,
  1294. "二、": 2,
  1295. "三、": 3,
  1296. "四、": 4,
  1297. "五、": 5,
  1298. "六、": 6,
  1299. "七、": 7,
  1300. "八、": 8,
  1301. "九、": 9,
  1302. "十、": 10,
  1303. "十一、": 11,
  1304. "十二、": 12,
  1305. "十三、": 13,
  1306. "十四、": 14,
  1307. "十五、": 15
  1308. }
  1309. for item in re.finditer(re_split, _content):
  1310. _index = split_dict.get(item.group()[1:])
  1311. if not split_list[_index]:
  1312. split_list[_index] = item.span()[0] + 1
  1313. split_list = [i for i in split_list if i != 0]
  1314. start = 0
  1315. new_split_list = []
  1316. for idx in split_list:
  1317. new_split_list.append((start, idx))
  1318. start = idx
  1319. new_split_list.append((start, len(_content)))
  1320. # 实体列表按照“公告分段”分组
  1321. words_num_dict = dict()
  1322. last_words_num = 0
  1323. for sentence in list_sentence:
  1324. _index = sentence.sentence_index
  1325. if _index == 0:
  1326. words_num_dict[_index] = 0
  1327. else:
  1328. words_num_dict[_index] = words_num_dict[_index - 1] + last_words_num
  1329. last_words_num = len(sentence.sentence_text)
  1330. # 公司-联系人连接(km算法)
  1331. re_phone = re.compile('1[3|4|5|6|7|8|9][0-9][-—-―]?\d{4}[-—-―]?\d{4}|'
  1332. '\+86.?1[3|4|5|6|7|8|9]\d{9}|'
  1333. '0[1-9]\d{1,2}[-—-―][1-9]\d{6,7}/[1-9]\d{6,10}|'
  1334. '0[1-9]\d{1,2}[-—-―]\d{7,8}.?转\d{1,4}|'
  1335. '0[1-9]\d{1,2}[-—-―]\d{7,8}[-—-―]\d{1,4}|'
  1336. '0[1-9]\d{1,2}[-—-―]?[1-9]\d{6}\d?(?=1[3|4|5|6|7|8|9]\d{9})|'
  1337. '0[1-9]\d{1,2}[-—-―]?[1-9]\d{6}\d?(?=0[1-9]\d{1,2}[-—-―]?[1-9]\d{6}\d?)|'
  1338. '0[1-9]\d{1,2}[-—-―]?[1-9]\d{6}\d?(?=[1-9]\d{6,7})|'
  1339. '0[1-9]\d{1,2}[-—-―]?[1-9]\d{6}\d?|'
  1340. '[\(|\(]0[1-9]\d{1,2}[\)|\)]-?\d{7,8}-?\d{,4}|'
  1341. '[2-9]\d{6,7}')
  1342. key_phone = re.compile("联系方式|电话|联系人|负责人")
  1343. temporary_list2 = []
  1344. for entity in list_entity:
  1345. # if entity.entity_type in ['org', 'company', 'person'] and entity.is_tail==False:
  1346. if entity.entity_type in ['org', 'company', 'person']:
  1347. temporary_list2.append(entity)
  1348. temporary_list2 = sorted(temporary_list2, key=lambda x: (x.sentence_index, x.begin_index))
  1349. new_temporary_list2 = []
  1350. for _split in new_split_list:
  1351. temp_list = []
  1352. for _entity in temporary_list2:
  1353. if words_num_dict[_entity.sentence_index] + _entity.wordOffset_begin >= _split[0] and words_num_dict[
  1354. _entity.sentence_index] + _entity.wordOffset_end < _split[1]:
  1355. temp_list.append(_entity)
  1356. elif words_num_dict[_entity.sentence_index] + _entity.wordOffset_begin >= _split[1]:
  1357. break
  1358. new_temporary_list2.append(temp_list)
  1359. # print(new_temporary_list2)
  1360. match_list2 = []
  1361. for split_index in range(len(new_temporary_list2)):
  1362. split_entitys = new_temporary_list2[split_index]
  1363. is_skip = False
  1364. for index in range(len(split_entitys)):
  1365. entity = split_entitys[index]
  1366. if is_skip:
  1367. is_skip = False
  1368. continue
  1369. else:
  1370. if entity.entity_type in ['org', 'company']:
  1371. if entity.label != 5 or entity.entity_text in roleSet:
  1372. match_nums = 0
  1373. for after_index in range(index + 1, min(len(split_entitys), index + 4)):
  1374. after_entity = split_entitys[after_index]
  1375. if after_entity.entity_type in ['person']:
  1376. # 实体为中标人/候选人,联系人已确定类别【1,2】
  1377. if entity.label in [2, 3, 4] and after_entity.label in [1, 2]:
  1378. break
  1379. if after_entity.label in [1, 2, 3]:
  1380. distance = (tokens_num_dict[
  1381. after_entity.sentence_index] + after_entity.begin_index) - (
  1382. tokens_num_dict[entity.sentence_index] + entity.end_index)
  1383. sentence_distance = after_entity.sentence_index - entity.sentence_index
  1384. if sentence_distance == 0:
  1385. if distance < 100:
  1386. if (entity.label == 0 and after_entity.label == 1) or (
  1387. entity.label == 1 and after_entity.label == 2):
  1388. distance = distance / 100
  1389. value = (-1 / 2 * (distance ** 2)) / 10000
  1390. match_list2.append(Match(entity, after_entity, value))
  1391. match_nums += 1
  1392. else:
  1393. if distance < 60:
  1394. if (entity.label == 0 and after_entity.label == 1) or (
  1395. entity.label == 1 and after_entity.label == 2):
  1396. distance = distance / 100
  1397. value = (-1 / 2 * (distance ** 2)) / 10000
  1398. match_list2.append(Match(entity, after_entity, value))
  1399. match_nums += 1
  1400. if after_entity.entity_type in ['org', 'company']:
  1401. # 解决在‘地址’中识别出org/company的问题
  1402. # if entity.label in [0,1] and after_index==index+1 and after_entity.label not in [0,1]:
  1403. if entity.label != 5 and after_index == index + 1 and (
  1404. after_entity.label == entity.label or after_entity.label == 5):
  1405. distance = (tokens_num_dict[
  1406. after_entity.sentence_index] + after_entity.begin_index) - (
  1407. tokens_num_dict[entity.sentence_index] + entity.end_index)
  1408. if distance < 20:
  1409. after_entity_left = list_sentence[after_entity.sentence_index].tokens[max(0,
  1410. after_entity.begin_index - 10):after_entity.begin_index]
  1411. after_entity_right = list_sentence[after_entity.sentence_index].tokens[
  1412. after_entity.end_index + 1:after_entity.end_index + 6]
  1413. after_entity_left = "".join(after_entity_left)
  1414. if len(after_entity_left) > 20:
  1415. after_entity_left = after_entity_left[-20:]
  1416. after_entity_right = "".join(after_entity_right)[:10]
  1417. if re.search("地,?址", after_entity_left):
  1418. is_skip = True
  1419. continue
  1420. if re.search("\(|(", after_entity_left) and re.search("\)|)",
  1421. after_entity_right):
  1422. is_skip = True
  1423. continue
  1424. if entity.label in [0, 1] and after_entity.label in [0,
  1425. 1] and entity.label == after_entity.label:
  1426. break
  1427. if entity.label in [0, 1] and after_entity.label in [0, 1] and split_entitys[
  1428. index + 1].entity_type == "person":
  1429. break
  1430. if entity.label in [0, 1] and after_entity.label in [2, 3, 4]:
  1431. break
  1432. if entity.label in [2, 3, 4] and after_entity.label in [0, 1]:
  1433. break
  1434. # 搜索没有联系人的电话
  1435. mid_tokens = []
  1436. is_same_sentence = False
  1437. if index == len(split_entitys) - 1:
  1438. for i in range(entity.sentence_index, len(list_sentence)):
  1439. mid_tokens += list_sentence[i].tokens
  1440. mid_tokens = mid_tokens[entity.end_index + 1:]
  1441. mid_sentence = "".join(mid_tokens)
  1442. have_phone = re.findall(re_phone, mid_sentence)
  1443. if have_phone:
  1444. if re.findall(re_phone, mid_sentence.split("。")[0]):
  1445. is_same_sentence = True
  1446. _phone = have_phone[0]
  1447. phone_begin = mid_sentence.find(_phone)
  1448. if words_num_dict[entity.sentence_index] + entity.wordOffset_begin + phone_begin < \
  1449. new_split_list[split_index][1]:
  1450. mid_sentence = mid_sentence[max(0, phone_begin - 15):phone_begin].replace(",", "")
  1451. if re.search(key_phone, mid_sentence):
  1452. distance = 1
  1453. if is_same_sentence:
  1454. if phone_begin <= 200:
  1455. value = (-1 / 2 * (distance ** 2)) / 10000
  1456. match_list2.append(Match(entity, (entity, _phone), value))
  1457. match_nums += 1
  1458. else:
  1459. if phone_begin <= 60:
  1460. value = (-1 / 2 * (distance ** 2)) / 10000
  1461. match_list2.append(Match(entity, (entity, _phone), value))
  1462. match_nums += 1
  1463. else:
  1464. next_entity = split_entitys[index + 1]
  1465. if entity.sentence_index == next_entity.sentence_index:
  1466. mid_tokens += list_sentence[entity.sentence_index].tokens[
  1467. entity.end_index + 1:next_entity.begin_index]
  1468. else:
  1469. sentence_index = entity.sentence_index
  1470. while sentence_index <= next_entity.sentence_index:
  1471. mid_tokens += list_sentence[sentence_index].tokens
  1472. sentence_index += 1
  1473. mid_tokens = mid_tokens[entity.end_index + 1:-(len(
  1474. list_sentence[next_entity.sentence_index].tokens) - next_entity.begin_index) + 1]
  1475. mid_sentence = "".join(mid_tokens)
  1476. have_phone = re.findall(re_phone, mid_sentence)
  1477. if have_phone:
  1478. if re.findall(re_phone, mid_sentence.split("。")[0]):
  1479. is_same_sentence = True
  1480. _phone = have_phone[0]
  1481. phone_begin = mid_sentence.find(_phone)
  1482. mid_sentence = mid_sentence[max(0, phone_begin - 15):phone_begin].replace(",", "")
  1483. if re.search(key_phone, mid_sentence):
  1484. p_phone = [p.entity_text for p in next_entity.person_phone] if next_entity.person_phone else []
  1485. if next_entity.entity_type == 'person' and _phone in p_phone:
  1486. pass
  1487. else:
  1488. distance = (tokens_num_dict[
  1489. next_entity.sentence_index] + next_entity.begin_index) - (
  1490. tokens_num_dict[entity.sentence_index] + entity.end_index)
  1491. distance = distance / 2
  1492. if is_same_sentence:
  1493. if phone_begin <= 200:
  1494. value = (-1 / 2 * (distance ** 2)) / 10000
  1495. match_list2.append(Match(entity, (entity, _phone), value))
  1496. match_nums += 1
  1497. else:
  1498. if phone_begin <= 60:
  1499. value = (-1 / 2 * (distance ** 2)) / 10000
  1500. match_list2.append(Match(entity, (entity, _phone), value))
  1501. match_nums += 1
  1502. # 实体无匹配时,尝试前向查找匹配
  1503. if not match_nums:
  1504. if entity.label != 5 and entity.values[entity.label] > 0.5 and index != 0:
  1505. previous_entity = split_entitys[index - 1]
  1506. if previous_entity.entity_type == 'person' and previous_entity.label in [1, 2, 3]:
  1507. if entity.label in [2, 3, 4] and previous_entity.label in [1, 2]:
  1508. continue
  1509. if previous_entity.sentence_index == entity.sentence_index:
  1510. distance = (tokens_num_dict[entity.sentence_index] + entity.begin_index) - (
  1511. tokens_num_dict[
  1512. previous_entity.sentence_index] + previous_entity.end_index)
  1513. if distance < 20:
  1514. # 距离相等时,前向添加处罚值
  1515. # distance += 1
  1516. # 前向 没有 /10000
  1517. value = (-1 / 2 * (distance ** 2))
  1518. match_list2.append(Match(entity, previous_entity, value))
  1519. # print(match_list2)
  1520. match_list2 = [mat for mat in match_list2 if mat.main_role not in linked_company and mat.attribute not in linked_person]
  1521. # print(match_list2)
  1522. # km算法分配求解
  1523. result2 = dispatch(match_list2)
  1524. # print(result2)
  1525. for match in result2:
  1526. entity = match[0]
  1527. # print(entity.entity_text)
  1528. # print(match.attribute)
  1529. entity_index = list_entity.index(entity)
  1530. is_update = False
  1531. if isinstance(match[1], tuple):
  1532. person_ = ''
  1533. phone_ = match[1][1].split("/") # 分割多个号码
  1534. # print(person_,phone_)
  1535. else:
  1536. person_ = match[1].entity_text
  1537. phone_ = [i.entity_text for i in match[1].person_phone] if match[1].person_phone else []
  1538. for k in PackDict.keys():
  1539. for i in range(len(PackDict[k]["roleList"])):
  1540. if PackDict[k]["roleList"][i].role_name == "tenderee":
  1541. if not PackDict[k]["roleList"][i].linklist:
  1542. if PackDict[k]["roleList"][i].entity_text == entity.entity_text or entity.label == 0:
  1543. if person_ not in agency_contact and len(set(phone_)&set(agency_phone))==0 and person_ not in winter_contact:
  1544. if not phone_:
  1545. PackDict[k]["roleList"][i].linklist.append((person_, ""))
  1546. for p in phone_:
  1547. # if not person_ and len()
  1548. PackDict[k]["roleList"][i].linklist.append((person_, p))
  1549. is_update = True
  1550. elif PackDict[k]["roleList"][i].role_name == "agency":
  1551. if not PackDict[k]["roleList"][i].linklist:
  1552. if PackDict[k]["roleList"][i].entity_text == entity.entity_text or entity.label == 1 and person_ not in winter_contact:
  1553. if person_ not in tenderee_contact and len(set(phone_)&set(tenderee_phone))==0:
  1554. if not phone_:
  1555. PackDict[k]["roleList"][i].linklist.append((person_, ""))
  1556. for p in phone_:
  1557. PackDict[k]["roleList"][i].linklist.append((person_, p))
  1558. is_update = True
  1559. else:
  1560. if PackDict[k]["roleList"][i].entity_text == entity.entity_text:
  1561. if not PackDict[k]["roleList"][i].linklist:
  1562. if person_ not in tenderee_contact and len(set(phone_)&set(tenderee_phone))==0 and \
  1563. person_ not in agency_contact and len(set(phone_)&set(agency_phone))==0:
  1564. if not phone_:
  1565. PackDict[k]["roleList"][i].linklist.append((person_, ""))
  1566. for p in phone_:
  1567. PackDict[k]["roleList"][i].linklist.append((person_, p))
  1568. is_update = True
  1569. if not person_:
  1570. is_update = False
  1571. if is_update:
  1572. # 更新 list_entity
  1573. if not list_entity[entity_index].pointer_person:
  1574. list_entity[entity_index].pointer_person = []
  1575. list_entity[entity_index].pointer_person.append(match[1])
  1576. linked_person = []
  1577. linked_persons_with = []
  1578. for company_entity in [entity for entity in list_entity if entity.entity_type in ['company','org']]:
  1579. if company_entity.pointer_person:
  1580. for _person in company_entity.pointer_person:
  1581. linked_person.append(_person)
  1582. linked_persons_with.append(company_entity)
  1583. # 一个公司对应多个联系人的补充
  1584. person_entitys = [entity for entity in list_entity if entity.entity_type=='person']
  1585. person_entitys = person_entitys[::-1]
  1586. for index in range(len(person_entitys)):
  1587. entity = person_entitys[index]
  1588. prepare_link = []
  1589. if entity not in linked_person:
  1590. prepare_link.append(entity)
  1591. last_person = entity
  1592. for after_index in range(index + 1, min(len(person_entitys), index + 5)):
  1593. after_entity = person_entitys[after_index]
  1594. if after_entity.sentence_index==last_person.sentence_index and last_person.begin_index-after_entity.end_index<5:
  1595. if after_entity in linked_person:
  1596. _index = linked_person.index(after_entity)
  1597. with_company = linked_persons_with[_index]
  1598. for i in range(len(PackDict["Project"]["roleList"])):
  1599. if PackDict["Project"]["roleList"][i].role_name == "tenderee":
  1600. if PackDict["Project"]["roleList"][i].entity_text == with_company.entity_text or with_company.label == 0:
  1601. for item in prepare_link:
  1602. person_phone = [p.entity_text for p in item.person_phone] if item.person_phone else []
  1603. for _p in person_phone:
  1604. PackDict["Project"]["roleList"][i].linklist.append((item.entity_text, _p))
  1605. with_company.pointer_person.append(item)
  1606. linked_person.append(item)
  1607. elif PackDict["Project"]["roleList"][i].role_name == "agency":
  1608. if PackDict["Project"]["roleList"][i].entity_text == with_company.entity_text or with_company.label == 1:
  1609. for item in prepare_link:
  1610. person_phone = [p.entity_text for p in item.person_phone] if item.person_phone else []
  1611. for _p in person_phone:
  1612. PackDict["Project"]["roleList"][i].linklist.append((item.entity_text, _p))
  1613. with_company.pointer_person.append(item)
  1614. linked_person.append(item)
  1615. else:
  1616. if PackDict["Project"]["roleList"][i].entity_text == with_company.entity_text:
  1617. for item in prepare_link:
  1618. person_phone = [p.entity_text for p in item.person_phone] if item.person_phone else []
  1619. for _p in person_phone:
  1620. PackDict["Project"]["roleList"][i].linklist.append((item.entity_text, _p))
  1621. with_company.pointer_person.append(item)
  1622. linked_person.append(item)
  1623. break
  1624. else:
  1625. prepare_link.append(after_entity)
  1626. last_person = after_entity
  1627. continue
  1628. # 统一同类角色的属性
  1629. if PackDict.get("Project"):
  1630. for i in range(len(PackDict["Project"]["roleList"])):
  1631. # if PackDict["Project"]["roleList"][i].role_name in ["tenderee","agency"]:
  1632. for _entity in list_entity:
  1633. if _entity.entity_type in ['org','company']:
  1634. is_similar = False
  1635. # entity_text相同
  1636. if _entity.entity_text==PackDict["Project"]["roleList"][i].entity_text:
  1637. is_similar = True
  1638. # entity.label为【0,1】
  1639. if _entity.label in [0,1] and dict_role_id[str(_entity.label)]==PackDict["Project"]["roleList"][i].role_name:
  1640. is_similar = True
  1641. if is_similar:
  1642. linked_entitys = _entity.linked_entitys
  1643. if linked_entitys:
  1644. for linked_entity in linked_entitys:
  1645. pointer_person = linked_entity.pointer_person if linked_entity.pointer_person else []
  1646. for _pointer_person in pointer_person:
  1647. _phone = [p.entity_text for p in _pointer_person.person_phone] if _pointer_person.person_phone else []
  1648. for _p in _phone:
  1649. if (_pointer_person.entity_text,_p) not in PackDict["Project"]["roleList"][i].linklist:
  1650. PackDict["Project"]["roleList"][i].linklist.append((_pointer_person.entity_text,_p))
  1651. # "roleList"中联系人电话去重
  1652. for i in range(len(PackDict["Project"]["roleList"])):
  1653. # print(123, PackDict["Project"]["roleList"][i].linklist)
  1654. # 带有联系人的电话
  1655. with_person = [person_phone[1] for person_phone in PackDict["Project"]["roleList"][i].linklist if person_phone[0]]
  1656. # 带有电话的联系人
  1657. with_phone = [person_phone[0] for person_phone in PackDict["Project"]["roleList"][i].linklist if person_phone[1]]
  1658. remove_list = []
  1659. for item in PackDict["Project"]["roleList"][i].linklist:
  1660. if not item[0]:
  1661. if item[1] in with_person:
  1662. # 删除重复的无联系人电话
  1663. remove_list.append(item)
  1664. elif not item[1]:
  1665. if item[0] in with_phone:
  1666. remove_list.append(item)
  1667. for _item in remove_list:
  1668. PackDict["Project"]["roleList"][i].linklist.remove(_item)
  1669. # 联系人——电子邮箱链接
  1670. 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])]
  1671. temporary_list3 = sorted(temporary_list3, key=lambda x: (x.sentence_index, x.begin_index))
  1672. new_temporary_list3 = []
  1673. for _split in new_split_list:
  1674. temp_list = []
  1675. for _entity in temporary_list3:
  1676. if words_num_dict[_entity.sentence_index] + _entity.wordOffset_begin >= _split[0] and words_num_dict[
  1677. _entity.sentence_index] + _entity.wordOffset_end < _split[1]:
  1678. temp_list.append(_entity)
  1679. elif words_num_dict[_entity.sentence_index] + _entity.wordOffset_begin >= _split[1]:
  1680. break
  1681. new_temporary_list3.append(temp_list)
  1682. # print(new_temporary_list3)
  1683. match_list3 = []
  1684. for split_index in range(len(new_temporary_list3)):
  1685. split_entitys = new_temporary_list3[split_index]
  1686. for index in range(len(split_entitys)):
  1687. entity = split_entitys[index]
  1688. if entity.entity_type == 'person':
  1689. match_nums = 0
  1690. for after_index in range(index + 1, min(len(split_entitys), index + 4)):
  1691. after_entity = split_entitys[after_index]
  1692. if match_nums > 2:
  1693. break
  1694. if after_entity.entity_type == 'email':
  1695. distance = (tokens_num_dict[after_entity.sentence_index] + after_entity.begin_index) - (
  1696. tokens_num_dict[entity.sentence_index] + entity.end_index)
  1697. sentence_distance = after_entity.sentence_index - entity.sentence_index
  1698. if sentence_distance == 0:
  1699. if distance < 100:
  1700. if (entity.label == 0 and after_entity.label == 1) or (
  1701. entity.label == 1 and after_entity.label == 2):
  1702. distance = distance / 100
  1703. value = (-1 / 2 * (distance ** 2)) / 10000
  1704. match_list3.append(Match(entity, after_entity, value))
  1705. match_nums += 1
  1706. else:
  1707. if distance < 60:
  1708. if (entity.label == 0 and after_entity.label == 1) or (
  1709. entity.label == 1 and after_entity.label == 2):
  1710. distance = distance / 100
  1711. value = (-1 / 2 * (distance ** 2)) / 10000
  1712. match_list3.append(Match(entity, after_entity, value))
  1713. match_nums += 1
  1714. # 前向查找匹配
  1715. # if not match_nums:
  1716. if index != 0:
  1717. previous_entity = split_entitys[index - 1]
  1718. if previous_entity.entity_type == 'email':
  1719. if previous_entity.sentence_index == entity.sentence_index:
  1720. distance = (tokens_num_dict[entity.sentence_index] + entity.begin_index) - (
  1721. tokens_num_dict[
  1722. previous_entity.sentence_index] + previous_entity.end_index)
  1723. if distance < 30:
  1724. # 距离相等时,前向添加处罚值
  1725. # distance += 1
  1726. # 前向 没有 /10000
  1727. value = (-1 / 2 * (distance ** 2))
  1728. match_list3.append(Match(entity, previous_entity, value))
  1729. # print(match_list3)
  1730. # km算法分配求解
  1731. result3 = dispatch(match_list3)
  1732. for match in result3:
  1733. match_person = match[0]
  1734. match_email = match[1]
  1735. match_person.pointer_email = match_email
  1736. # # 1)第一个公司实体的招标人,则看看下一个实体是否为代理人,如果是则联系人错位连接 。2)在同一句中往后找联系人。3)连接不上在整个文章找联系人。
  1737. # temp_ent_list = [] # 临时列表,记录0,1角色及3联系人
  1738. # other_person = [] # 阈值以上的联系人列表
  1739. # link_person = [] # 有电话没联系上角色的person列表
  1740. # other_ent = []
  1741. # link_ent = []
  1742. # found_person = False
  1743. # ent_list = []
  1744. # for entity in list_entity:
  1745. # if entity.entity_type in ['org','company','person']:
  1746. # ent_list.append(entity)
  1747. # # ent_list = [entity for entity in list_entity if entity.entity_type in ['org','company','person']]
  1748. # #for list_index in range(len(ent_list)):
  1749. # #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 \
  1750. # #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']:
  1751. # #ent_list[list_index+1], ent_list[list_index+2] = ent_list[list_index+2], ent_list[list_index+1]
  1752. # # 2020/11/25增加确定角色联系人判断
  1753. # sure_person_set = set([entity.entity_text for entity in ent_list if entity.entity_type == 'person' and entity.label in [1, 2]])
  1754. # # 招标/代理在同一句中交叉情况的处理
  1755. # for index in range(len(ent_list)):
  1756. # entity = ent_list[index]
  1757. # if entity.entity_text in roleSet and entity.label in [0, 1] and index+3<len(ent_list):
  1758. # if entity.sentence_index==ent_list[index+1].sentence_index==ent_list[index+2].sentence_index==ent_list[index+3].sentence_index:
  1759. # if ent_list[index+1].begin_index - entity.end_index < 30:
  1760. # 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:
  1761. # if ent_list[index+2].entity_type=="person" and ent_list[index+3].entity_type=="person" and \
  1762. # ent_list[index+2].label==3 and ent_list[index+3].label==3:
  1763. # ent_list[index + 1], ent_list[index + 2] = ent_list[index + 2], ent_list[index + 1]
  1764. #
  1765. #
  1766. # for index in range(len(ent_list)):
  1767. # entity = ent_list[index]
  1768. # if entity.entity_type=="person":
  1769. # if str(entity.label) == "0": # 2020/11/25 非联系人直接跳过
  1770. # continue
  1771. # if entity.values[entity.label]>on_value_person:
  1772. # if str(entity.label)=="1":
  1773. # for i in range(len(PackDict["Project"]["roleList"])):
  1774. # if PackDict["Project"]["roleList"][i].role_name=="tenderee":
  1775. # PackDict["Project"]["roleList"][i].linklist.append((entity.entity_text,entity.person_phone))
  1776. # link_person.append(entity.entity_text)
  1777. # link_ent.append(PackDict["Project"]["roleList"][i].entity_text)
  1778. # # add pointer_person
  1779. # for _entity in list_entity:
  1780. # if dict_role_id.get(str(_entity.label))=="tenderee":
  1781. # for i in range(len(PackDict["Project"]["roleList"])):
  1782. # if PackDict["Project"]["roleList"][i].entity_text==_entity.entity_text and PackDict["Project"]["roleList"][i].role_name=="tenderee":
  1783. # _entity.pointer_person = entity
  1784. # elif str(entity.label)=="2":
  1785. # for i in range(len(PackDict["Project"]["roleList"])):
  1786. # if PackDict["Project"]["roleList"][i].role_name=="agency":
  1787. # PackDict["Project"]["roleList"][i].linklist.append((entity.entity_text,entity.person_phone))
  1788. # link_person.append(entity.entity_text)
  1789. # link_ent.append(PackDict["Project"]["roleList"][i].entity_text)
  1790. # # add pointer_person
  1791. # for _entity in list_entity:
  1792. # if dict_role_id.get(str(_entity.label))=="agency":
  1793. # for i in range(len(PackDict["Project"]["roleList"])):
  1794. # if PackDict["Project"]["roleList"][i].entity_text==_entity.entity_text and PackDict["Project"]["roleList"][i].role_name=="agency":
  1795. # _entity.pointer_person = entity
  1796. # elif str(entity.label)=="3":
  1797. # if entity.entity_text in sure_person_set: # 2020/11/25 排除已经确定角色的联系人
  1798. # continue
  1799. # #not_link_person.append((entity_after.entity_text,entity_after.person_phone))
  1800. # other_person.append(entity.entity_text)
  1801. # temp_ent_list.append((entity.entity_text,entity.person_phone,entity))
  1802. #
  1803. # #if entity.entity_text in roleSet:
  1804. # if entity.entity_text in roleSet:
  1805. # if entity.label in [0,1]:
  1806. # other_ent.append(entity.entity_text)
  1807. # temp_ent_list.append((entity.entity_text, entity.label,entity))
  1808. # for behind_index in range(index+1, len(ent_list)):
  1809. # entity_after = ent_list[behind_index]
  1810. # if entity_after.sentence_index-entity.sentence_index>=1 or entity_after.entity_type in ['org','company']: # 只在本句中找联系人
  1811. # break
  1812. # if entity_after.values is not None:
  1813. # if entity_after.entity_type=="person":
  1814. # if str(entity_after.label) == "0": # 2020/11/25角色后面为非联系人 停止继续往后找
  1815. # break
  1816. # if entity_after.values[entity_after.label]>on_value_person:
  1817. # if str(entity_after.label)=="1":
  1818. # for i in range(len(PackDict["Project"]["roleList"])):
  1819. # if PackDict["Project"]["roleList"][i].role_name=="tenderee":
  1820. # PackDict["Project"]["roleList"][i].linklist.append((entity_after.entity_text,entity_after.person_phone))
  1821. # link_person.append(entity_after.entity_text)
  1822. # link_ent.append(PackDict["Project"]["roleList"][i].entity_text)
  1823. # elif str(entity_after.label)=="2":
  1824. # for i in range(len(PackDict["Project"]["roleList"])):
  1825. # if PackDict["Project"]["roleList"][i].role_name=="agency":
  1826. # PackDict["Project"]["roleList"][i].linklist.append((entity_after.entity_text,entity_after.person_phone))
  1827. # link_person.append(entity_after.entity_text)
  1828. # link_ent.append(PackDict["Project"]["roleList"][i].entity_text)
  1829. # elif str(entity_after.label)=="3":
  1830. # if entity_after.entity_text in sure_person_set: # 2020/11/25 如果姓名已经出现在确定角色联系人中则停止往后找
  1831. # break
  1832. # elif entity_after.begin_index - entity.end_index > 30:#2020/10/25 如果角色实体与联系人实体间隔大于阈值停止
  1833. # break
  1834. # for pack in PackDict.keys():
  1835. # for i in range(len(PackDict[pack]["roleList"])):
  1836. # if PackDict[pack]["roleList"][i].entity_text==entity.entity_text:
  1837. # #if entity_after.sentence_index-entity.sentence_index>1 and len(roleList[i].linklist)>0:
  1838. # #break
  1839. # PackDict[pack]["roleList"][i].linklist.append((entity_after.entity_text,entity_after.person_phone))
  1840. # link_person.append(entity_after.entity_text)
  1841. # #add pointer_person
  1842. # entity.pointer_person = entity_after
  1843. #
  1844. # not_link_person = [person for person in other_person if person not in link_person]
  1845. # not_link_ent = [ent for ent in other_ent if ent not in link_ent]
  1846. # if len(not_link_person) > 0 and len(not_link_ent) > 0 :
  1847. # item = temp_ent_list
  1848. # for i in range(len(item)):
  1849. # if item[i][0] in not_link_ent and item[i][1] == 0 and i+3 < len(item):
  1850. # 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:
  1851. # item[i+1], item[i+2] = item[i+2], item[i+1]
  1852. # for i in range(len(item)-1, -1, -1):
  1853. # if item[i][0] in not_link_ent:
  1854. # for pack in PackDict.keys():
  1855. # for role in PackDict[pack]["roleList"]:
  1856. # if role.entity_text == item[i][0] and len(role.linklist) < 1:
  1857. # for j in range(i+1, len(item)):
  1858. # if item[j][0] in not_link_person:
  1859. # role.linklist.append(item[j][:2])
  1860. # #add pointer_person
  1861. # item[i][2].pointer_person = item[j][2]
  1862. # break
  1863. # else:
  1864. # break
  1865. # # 电话没有联系人的处理
  1866. # role_with_no_phone = []
  1867. # for i in range(len(PackDict["Project"]["roleList"])):
  1868. # if PackDict["Project"]["roleList"][i].role_name in ["tenderee","agency"]:
  1869. # if len(PackDict["Project"]["roleList"][i].linklist)==0: # 找出没有联系人的招标/代理人
  1870. # role_with_no_phone.append(PackDict["Project"]["roleList"][i].entity_text)
  1871. # else:
  1872. # phone_nums = 0
  1873. # for link in PackDict["Project"]["roleList"][i].linklist:
  1874. # if link[1]:
  1875. # phone_nums += 1
  1876. # break
  1877. # if not phone_nums:
  1878. # role_with_no_phone.append(PackDict["Project"]["roleList"][i].entity_text)
  1879. # if role_with_no_phone:
  1880. # phone_with_person = [entity.person_phone for entity in list_entity if entity.entity_type == "person"]
  1881. # # phone_with_person = [phone for phone in phone_with_person if phone]
  1882. #
  1883. # dict_index_sentence = {}
  1884. # for _sentence in list_sentence:
  1885. # dict_index_sentence[_sentence.sentence_index] = _sentence
  1886. # new_entity_list = [entity for entity in list_entity if entity.entity_type in ['org','company','person']]
  1887. # for index in range(len(new_entity_list)):
  1888. # entity = new_entity_list[index]
  1889. # if entity.entity_text in role_with_no_phone:
  1890. # e_sentence = dict_index_sentence[entity.sentence_index]
  1891. # entity_right = e_sentence.tokens[entity.end_index:entity.end_index+40]
  1892. # entity_right = "".join(entity_right)
  1893. # if index+1<len(new_entity_list) and entity_right.find(new_entity_list[index+1].entity_text)>-1:
  1894. # entity_right = entity_right[:entity_right.find(new_entity_list[index+1].entity_text)]
  1895. # have_phone = re.findall(phone,entity_right)
  1896. # if have_phone:
  1897. # _phone = have_phone[0]
  1898. # phone_begin = entity_right.find(_phone)
  1899. # if _phone not in phone_with_person and re.search(key_phone,entity_right[:phone_begin]):
  1900. # # entity.person_phone = _phone
  1901. # for i in range(len(PackDict["Project"]["roleList"])):
  1902. # if PackDict["Project"]["roleList"][i].entity_text == entity.entity_text:
  1903. # PackDict["Project"]["roleList"][i].linklist.append(('', _phone))
  1904. #寻找多标段招标金额
  1905. p_entity = len(list_entity)-1
  1906. set_tenderer_money = set()
  1907. list_tenderer_money = [] #2021/7/16 新增列表,倒序保存所有中标金额
  1908. unit_list = [] #2021/8/17 新增,保存金额单位
  1909. #遍历所有实体
  1910. while(p_entity>=0):
  1911. entity = list_entity[p_entity]
  1912. if entity.entity_type=="money":
  1913. # 2021/12/03 添加成本警戒线、保证金
  1914. if entity.notes in ['保证金', '成本警戒线']:
  1915. packagePointer, _flag = getPackage(PackageList, entity.sentence_index, entity.begin_index,
  1916. "money-" + str(entity.label), MAX_DIS=2, DIRECT="L")
  1917. if packagePointer is None:
  1918. packageName = "Project"
  1919. else:
  1920. packageName = packagePointer.entity_text
  1921. if packageName == "Project":
  1922. # if PackDict["Project"]["tendereeMoney"]<float(entity.entity_text):
  1923. # PackDict["Project"]["tendereeMoney"] = float(entity.entity_text)
  1924. if entity.notes=="保证金" and "bond" not in PackDict["Project"]:
  1925. PackDict["Project"]["bond"] = float(entity.entity_text)
  1926. elif entity.notes=="成本警戒线" and "cost_warning" not in PackDict["Project"]:
  1927. PackDict["Project"]["cost_warning"] = float(entity.entity_text)
  1928. else:
  1929. if entity.notes == "保证金" and "bond" not in PackDict[packageName]:
  1930. PackDict[packageName]["bond"] = float(entity.entity_text)
  1931. elif entity.notes == "成本警戒线" and "cost_warning" not in PackDict[packageName]:
  1932. PackDict[packageName]["cost_warning"] = float(entity.entity_text)
  1933. elif entity.values[entity.label]>=on_value:
  1934. if str(entity.label)=="1":
  1935. set_tenderer_money.add(float(entity.entity_text))
  1936. list_tenderer_money.append(float(entity.entity_text)) # 2021/7/16 新增列表,倒序保存所有中标金额
  1937. unit_list.append(entity.money_unit)
  1938. # if str(entity.label)=="0":
  1939. if str(entity.label)=="0" and entity.notes!='总投资':
  1940. '''
  1941. if p_entity>0:
  1942. p_before = list_entity[p_entity-1]
  1943. 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:
  1944. p_entity -= 1
  1945. continue
  1946. '''
  1947. packagePointer,_flag = getPackage(PackageList,entity.sentence_index,entity.begin_index,"money-"+str(entity.label),MAX_DIS=2,DIRECT="L")
  1948. if packagePointer is None:
  1949. packageName = "Project"
  1950. else:
  1951. packageName = packagePointer.entity_text
  1952. if packageName=="Project":
  1953. # if PackDict["Project"]["tendereeMoney"]<float(entity.entity_text):
  1954. # PackDict["Project"]["tendereeMoney"] = float(entity.entity_text)
  1955. if entity.values[entity.label]>on_value:
  1956. PackDict["Project"]["tendereeMoney"] = float(entity.entity_text)
  1957. PackDict["Project"]["tendereeMoneyUnit"] = entity.money_unit
  1958. else:
  1959. PackDict[packageName]["tendereeMoney"] = float(entity.entity_text)
  1960. PackDict[packageName]["tendereeMoneyUnit"] = entity.money_unit
  1961. #add pointer_tendereeMoney
  1962. packagePointer.pointer_tendereeMoney = entity
  1963. p_entity -= 1
  1964. #删除一个机构有多个角色的数据
  1965. #删除重复人、概率不回传
  1966. final_roleList = []
  1967. list_pop = []
  1968. set_tenderer_role = set()
  1969. dict_pack_tenderer_money = dict()
  1970. for pack in PackDict.keys():
  1971. #删除无效包
  1972. if PackDict[pack]["code"]=="" and PackDict[pack]["tendereeMoney"]==0 and len(PackDict[pack]["roleList"])==0:
  1973. list_pop.append(pack)
  1974. for i in range(len(PackDict[pack]["roleList"])):
  1975. if PackDict[pack]["roleList"][i].role_name=="win_tenderer":
  1976. if PackDict[pack]["roleList"][i].money==0:
  1977. set_tenderer_role.add(PackDict[pack]["roleList"][i])
  1978. dict_pack_tenderer_money[pack] = [PackDict[pack]["roleList"][i],set()]
  1979. #找到包的中投标金额
  1980. for _index in range(len(PackageList)):
  1981. if "hit" in PackageList[_index]:
  1982. for _hit in list(PackageList[_index]["hit"]):
  1983. _money = float(_hit.split("-")[1]) if _hit.split("-")[0]=="money" else None
  1984. if PackageList[_index]["name"] in dict_pack_tenderer_money and _money is not None:
  1985. dict_pack_tenderer_money[PackageList[_index]["name"]][1].add(_money)
  1986. #只找到一个中标人和中标金额
  1987. if len(set_tenderer_money)==1 and len(set_tenderer_role)==1:
  1988. list(set_tenderer_role)[0].money = list(set_tenderer_money)[0]
  1989. list(set_tenderer_role)[0].money_unit = unit_list[0]
  1990. # print('一个中标人一个金额:', list(set_tenderer_money)[0])
  1991. #找到一个中标人和多个招标金额
  1992. if len(set_tenderer_money)>1 and len(set_tenderer_role)==1:
  1993. _maxMoney = 0
  1994. _sumMoney = 0
  1995. for _m in list(set_tenderer_money):
  1996. _sumMoney += _m
  1997. if _m>_maxMoney:
  1998. _maxMoney = _m
  1999. if _sumMoney/_maxMoney==2:
  2000. list(set_tenderer_role)[0].money = _maxMoney
  2001. # print('一人多金额分项合计 取最大金额:', _maxMoney)
  2002. else:
  2003. # list(set_tenderer_role)[0].money = _maxMoney
  2004. if min(list_tenderer_money)>200000 and list_tenderer_money[-1]/min(list_tenderer_money)>9000:
  2005. list(set_tenderer_role)[0].money = min(list_tenderer_money)
  2006. list(set_tenderer_role)[0].money_unit = unit_list[list_tenderer_money.index(min(list_tenderer_money))]
  2007. # print('一人多金额 且最小的大于20万第一个金额比最小金额大几千倍的最小中标金额:', min(list_tenderer_money))
  2008. else:
  2009. list(set_tenderer_role)[0].money = list_tenderer_money[-1] # 2021/7/16 修改 不是单价合计方式取第一个中标金额
  2010. list(set_tenderer_role)[0].money_unit = unit_list[-1] # 金额单位
  2011. # print('一人多金额 取第一个中标金额:', list_tenderer_money[-1])
  2012. #每个包都只找到一个金额
  2013. _flag_pack_money = True
  2014. for k,v in dict_pack_tenderer_money.items():
  2015. if len(v[1])!=1:
  2016. _flag_pack_money = False
  2017. if _flag_pack_money and len(PackageSet)==len(dict_pack_tenderer_money.keys()):
  2018. for k,v in dict_pack_tenderer_money.items():
  2019. v[0].money = list(v[1])[0]
  2020. # print('k,v in dict_pack_tenderer_money.items', k, v)
  2021. # 2021/7/16 #增加判断中标金额是否远大于招标金额逻辑
  2022. for pack in PackDict.keys():
  2023. for i in range(len(PackDict[pack]["roleList"])):
  2024. if PackDict[pack]["tendereeMoney"] > 0:
  2025. # print('金额数据类型:',type(PackDict[pack]["roleList"][i].money))
  2026. if float(PackDict[pack]["roleList"][i].money) >10000000 and \
  2027. float(PackDict[pack]["roleList"][i].money)/float(PackDict[pack]["tendereeMoney"])>=1000:
  2028. PackDict[pack]["roleList"][i].money = float(PackDict[pack]["roleList"][i].money) / 10000
  2029. # print('招标金额校正中标金额')
  2030. # 2021/7/19 #增加判断中标金额是否远大于第二三中标金额
  2031. for pack in PackDict.keys():
  2032. tmp_moneys = []
  2033. for i in range(len(PackDict[pack]["roleList"])):
  2034. if float(PackDict[pack]["roleList"][i].money) >100000:
  2035. tmp_moneys.append(float(PackDict[pack]["roleList"][i].money))
  2036. if len(tmp_moneys)>2 and max(tmp_moneys)/min(tmp_moneys)>1000:
  2037. for i in range(len(PackDict[pack]["roleList"])):
  2038. if float(PackDict[pack]["roleList"][i].money)/min(tmp_moneys)>1000:
  2039. PackDict[pack]["roleList"][i].money = float(PackDict[pack]["roleList"][i].money) / 10000
  2040. # print('通过其他中标人投标金额校正中标金额')
  2041. for pack in PackDict.keys():
  2042. for i in range(len(PackDict[pack]["roleList"])):
  2043. PackDict[pack]["roleList"][i] = PackDict[pack]["roleList"][i].getString()
  2044. for item in list_pop:
  2045. PackDict.pop(item)
  2046. return PackDict
  2047. def initPackageAttr(RoleList,PackageSet):
  2048. '''
  2049. @summary: 根据拿到的roleList和packageSet初始化接口返回的数据
  2050. '''
  2051. packDict = dict()
  2052. packDict["Project"] = {"code":"","tendereeMoney":0,"roleList":[], 'tendereeMoneyUnit':''}
  2053. for item in list(PackageSet):
  2054. packDict[item] = {"code":"","tendereeMoney":0,"roleList":[], 'tendereeMoneyUnit':''}
  2055. for item in RoleList:
  2056. if packDict[item.packageName]["code"] =="":
  2057. packDict[item.packageName]["code"] = item.packageCode
  2058. # packDict[item.packageName]["roleList"].append(Role(item.role_name,item.entity_text,0,0,0.0,[]))
  2059. packDict[item.packageName]["roleList"].append(Role(item.role_name,item.entity_text,0,0,0.0,[])) #Role(角色名称,实体名称,角色阈值,金额,金额阈值,连接列表,金额单位)
  2060. return packDict
  2061. def getPackageRoleMoney(list_sentence,list_entity):
  2062. '''
  2063. @param:
  2064. list_sentence:文章的句子list
  2065. list_entity:文章的实体list
  2066. @return: 拿到文章的包-标段号-角色-实体名称-金额-联系人-联系电话
  2067. '''
  2068. # print("=1")
  2069. theRole = getRoleList(list_sentence,list_entity)
  2070. if not theRole:
  2071. return []
  2072. RoleList,RoleSet,PackageList,PackageSet = theRole
  2073. '''
  2074. for item in PackageList:
  2075. # print(item)
  2076. '''
  2077. # print("=2")
  2078. PackDict = initPackageAttr(RoleList, PackageSet)
  2079. # print("=3")
  2080. PackDict = findAttributeAfterEntity(PackDict, RoleSet, PackageList, PackageSet, list_entity, list_sentence)
  2081. # print("=4")
  2082. return PackDict
  2083. def turnBidWay(bidway):
  2084. if bidway in ("邀请招标","采购方式:邀请"):
  2085. return "邀请招标"
  2086. elif bidway in ("询价","询单","询比","采购方式:询价"):
  2087. return "询价"
  2088. elif bidway in ("竞谈","竞争性谈判","公开竞谈"):
  2089. return "竞争性谈判"
  2090. elif bidway in ("竞争性磋商","磋商"):
  2091. return "竞争性磋商"
  2092. elif bidway in ("竞价","竞标","电子竞价","以电子竞价","电子书面竞投"):
  2093. return "竞价"
  2094. elif bidway in ("公开招标","网上电子投标","网上招标","采购方式:公开","招标为其他"):
  2095. return "公开招标"
  2096. elif bidway in ("单一来源"):
  2097. return "单一来源"
  2098. elif bidway in ("比选"):
  2099. return "比选"
  2100. else:
  2101. return "其他"
  2102. def getOtherAttributes(list_entity):
  2103. dict_other = {"moneysource":"",
  2104. "person_review":[],
  2105. "time_release":"",
  2106. "time_bidopen":"",
  2107. "time_bidclose":"",
  2108. "serviceTime":"",
  2109. "product":[],
  2110. "total_tendereeMoney":0,
  2111. "total_tendereeMoneyUnit":''
  2112. }
  2113. dict_time = {
  2114. "time_release": [],
  2115. "time_bidopen": [],
  2116. "time_bidclose": []
  2117. }
  2118. for entity in list_entity:
  2119. if entity.entity_type == 'bidway':
  2120. dict_other["bidway"] = turnBidWay(entity.entity_text)
  2121. elif entity.entity_type=='moneysource':
  2122. dict_other["moneysource"] = entity.entity_text
  2123. elif entity.entity_type=='serviceTime':
  2124. dict_other["serviceTime"] = entity.entity_text
  2125. elif entity.entity_type == 'time' and entity.label==1:
  2126. if entity.values[entity.label]>0.6:
  2127. dict_time['time_release'].append((timeFormat(entity.entity_text),entity.values[entity.label]))
  2128. # dict_other["time_release"] = timeFormat(entity.entity_text)
  2129. elif entity.entity_type == 'time' and entity.label==2:
  2130. if entity.values[entity.label]>0.6:
  2131. dict_time['time_bidopen'].append((timeFormat(entity.entity_text),entity.values[entity.label]))
  2132. # dict_other["time_bidopen"] = timeFormat(entity.entity_text)
  2133. elif entity.entity_type == 'time' and entity.label == 3:
  2134. if entity.values[entity.label]>0.6:
  2135. dict_time['time_bidclose'].append((timeFormat(entity.entity_text),entity.values[entity.label]))
  2136. # dict_other["time_bidclose"] = timeFormat(entity.entity_text)
  2137. elif entity.entity_type=="person" and entity.label ==4:
  2138. dict_other["person_review"].append(entity.entity_text)
  2139. elif entity.entity_type=='product':
  2140. dict_other["product"].append(entity.entity_text)
  2141. elif entity.entity_type=='money' and entity.notes=='总投资' and dict_other["total_tendereeMoney"]<float(entity.entity_text):
  2142. dict_other["total_tendereeMoney"] = float(entity.entity_text)
  2143. dict_other["total_tendereeMoneyUnit"] = entity.money_unit
  2144. # 时间类别
  2145. for time_type,value in dict_time.items():
  2146. list_time = dict_time[time_type]
  2147. if list_time:
  2148. list_time.sort(key=lambda x:x[1],reverse=True)
  2149. dict_other[time_type] = list_time[0][0]
  2150. dict_other["product"] = list(set(dict_other["product"]))
  2151. return dict_other
  2152. def getMoneyRange(RoleList):
  2153. pass
  2154. def getPREMs(list_sentences,list_entitys,list_articles):
  2155. '''
  2156. @param:
  2157. list_sentence:所有文章的句子list
  2158. list_entity:所有文章的实体list
  2159. @return:list of dict which include文章的包-角色-实体名称-金额-联系人-联系电话
  2160. '''
  2161. result = []
  2162. for list_sentence,list_entity,list_article in zip(list_sentences,list_entitys,list_articles):
  2163. RoleList = getPackageRoleMoney(list_sentence,list_entity)
  2164. result.append(dict({"prem":RoleList,"docid":list_article.id},**getOtherAttributes(list_entity),
  2165. **{"fingerprint":list_article.fingerprint,"match_enterprise":list_article.match_enterprise,
  2166. "match_enterprise_type":list_article.match_enterprise_type,"process_time":getCurrent_date(),
  2167. "attachmentTypes":list_article.attachmentTypes, "bidway": list_article.bidway}))
  2168. return result
  2169. if __name__=="__main__":
  2170. '''
  2171. conn = getConnection()
  2172. cursor = conn.cursor()
  2173. #sql = " select distinct A.doc_id from entity_mention A,test_predict_role B where A.entity_id=B.entity_id limit 200"
  2174. sql = " select B.doc_id,B.prem from articles_processed A, articles_validation B where A.id=B.doc_id "
  2175. result = []
  2176. cursor.execute(sql)
  2177. rows = cursor.fetchall()
  2178. count = 0
  2179. for row in rows:
  2180. count += 1
  2181. # print(count)
  2182. doc_id = row[0]
  2183. roleList = getPackageRoleMoney(doc_id)
  2184. result.append([doc_id,str(roleList),row[1]])
  2185. ''''''
  2186. with codecs.open("getAttribute.html","w",encoding="utf8") as f:
  2187. f.write('<html><head>\
  2188. <meta http-equiv="Content-Type"\
  2189. content="text/html; charset=UTF-8">\
  2190. </head>\
  2191. <body bgcolor="#FFFFFF">\
  2192. <table border="1">\
  2193. <tr>\
  2194. <td>doc_id</td>\
  2195. <td>角色</td>\
  2196. </tr>')
  2197. for item in result:
  2198. f.write("<tr>"+"<td>"+item[0]+"</td>"+"<td>"+item[1]+"</td>"+"<td>"+item[2]+"</td>"+"</tr>")
  2199. f.write("</table></body>")
  2200. '''