entityLink.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323
  1. '''
  2. Created on 2019年5月21日
  3. @author: User
  4. '''
  5. import re
  6. import os
  7. import time
  8. _time = time.time()
  9. from BiddingKG.dl.common.Utils import *
  10. from BiddingKG.dl.interface.Entitys import *
  11. import json
  12. def edit_distance(source,target):
  13. dp = [["" for i in range(len(source)+1)] for j in range(len(target)+1)]
  14. for i in range(len(dp)):
  15. for j in range(len(dp[i])):
  16. if i==0:
  17. dp[i][j] = j
  18. elif j==0:
  19. dp[i][j] = i
  20. else:
  21. if source[j-1]==target[i-1]:
  22. cost = 0
  23. else:
  24. cost = 2
  25. dp[i][j] = min([dp[i-1][j]+1,dp[i][j-1]+1,dp[i-1][j-1]+cost])
  26. return dp[-1][-1]
  27. def jaccard_score(source,target):
  28. source_set = set([s for s in source])
  29. target_set = set([s for s in target])
  30. if len(source_set)==0 or len(target_set)==0:
  31. return 0
  32. return max(len(source_set&target_set)/len(source_set),len(source_set&target_set)/len(target_set))
  33. def link_entitys(list_entitys,on_value=0.8):
  34. for list_entity in list_entitys:
  35. range_entity = []
  36. for _entity in list_entity:
  37. if _entity.entity_type in ["org","company"]:
  38. range_entity.append(_entity)
  39. range_entity = range_entity[:1000]
  40. for first_i in range(len(range_entity)):
  41. _entity = range_entity[first_i]
  42. for second_i in range(first_i+1,len(range_entity)):
  43. _ent = range_entity[second_i]
  44. # 2021/5/21 update: 两个实体标签互斥(一个是招标人、一个是代理人)且entity_text不相等时,跳过
  45. if _entity.entity_text != _ent.entity_text and _entity.label != _ent.label and _entity.label in [0,1] and _ent.label in [0, 1]:
  46. continue
  47. _score = jaccard_score(_entity.entity_text, _ent.entity_text)
  48. if _entity.entity_text!=_ent.entity_text and _score>=on_value:
  49. _entity.linked_entitys.append(_ent)
  50. _ent.linked_entitys.append(_entity)
  51. #替换公司名称
  52. for _entity in range_entity:
  53. if re.search("公司",_entity.entity_text) is None:
  54. for _ent in _entity.linked_entitys:
  55. if re.search("公司$",_ent.entity_text) is not None:
  56. if len(_ent.entity_text)>len(_entity.entity_text):
  57. _entity.entity_text = _ent.entity_text
  58. def getEnterprisePath():
  59. filename = "LEGAL_ENTERPRISE.txt"
  60. filepath = os.path.dirname(__file__)+"/../"
  61. real_path = filename
  62. if os.path.exists(filepath+filename):
  63. real_path = filepath+filename
  64. return real_path
  65. DICT_ENTERPRISE = {}
  66. DICT_ENTERPRISE_DONE = False
  67. def getDict_enterprise():
  68. global DICT_ENTERPRISE,DICT_ENTERPRISE_DONE
  69. real_path = getEnterprisePath()
  70. with open(real_path,"r",encoding="UTF8") as f:
  71. for _e in f:
  72. if not _e:
  73. continue
  74. _e = _e.strip()
  75. if len(_e)>=4:
  76. key_enter = _e[:4]
  77. if key_enter not in DICT_ENTERPRISE:
  78. DICT_ENTERPRISE[key_enter] = set()
  79. DICT_ENTERPRISE[key_enter].add(_e[4:])
  80. # for _e in ["河南省柘源","建筑工程有限公司"]:
  81. # if not _e:
  82. # continue
  83. # _e = _e.strip()
  84. # if len(_e)>=4:
  85. # key_enter = _e[:4]
  86. # if key_enter not in DICT_ENTERPRISE:
  87. # DICT_ENTERPRISE[key_enter] = set()
  88. # DICT_ENTERPRISE[key_enter].add(_e[4:])
  89. DICT_ENTERPRISE_DONE = True
  90. return DICT_ENTERPRISE
  91. import threading
  92. import time
  93. load_enterprise_thread = threading.Thread(target=getDict_enterprise)
  94. load_enterprise_thread.start()
  95. MAX_ENTERPRISE_LEN = 30
  96. def match_enterprise_max_first(sentence):
  97. while True:
  98. if not DICT_ENTERPRISE_DONE:
  99. time.sleep(1)
  100. else:
  101. break
  102. list_match = []
  103. begin_index = 0
  104. if len(sentence)>4:
  105. while True:
  106. if begin_index+4<len(sentence):
  107. key_enter = sentence[begin_index:begin_index+4]
  108. if key_enter in DICT_ENTERPRISE:
  109. for _i in range(MAX_ENTERPRISE_LEN-4+1):
  110. enter_name = sentence[begin_index+4:begin_index+MAX_ENTERPRISE_LEN-_i]
  111. if enter_name in DICT_ENTERPRISE[key_enter]:
  112. match_item = {"entity_text":"%s%s"%(key_enter,enter_name),"begin_index":begin_index,"end_index":begin_index+len(key_enter)+len(enter_name)}
  113. list_match.append(match_item)
  114. begin_index += (len(key_enter)+len(enter_name))-1
  115. break
  116. begin_index += 1
  117. else:
  118. break
  119. return list_match
  120. def calibrateEnterprise(list_articles,list_sentences,list_entitys):
  121. for _article,list_sentence,list_entity in zip(list_articles,list_sentences,list_entitys):
  122. list_calibrate = []
  123. match_add = False
  124. match_replace = False
  125. range_entity = []
  126. for p_entity in list_entity:
  127. if p_entity.entity_type in ("org","company","location"):
  128. range_entity.append(p_entity)
  129. if len(range_entity)>1000:
  130. break
  131. for p_sentence in list_sentence:
  132. sentence = p_sentence.sentence_text
  133. list_match = match_enterprise_max_first(sentence)
  134. doc_id = p_sentence.doc_id
  135. sentence_index = p_sentence.sentence_index
  136. tokens = p_sentence.tokens
  137. list_match.sort(key=lambda x:x["begin_index"])
  138. for _match_index in range(len(list_match)):
  139. _match = list_match[_match_index]
  140. find_flag = False
  141. for p_entity in range_entity:
  142. if p_entity.sentence_index!=p_sentence.sentence_index:
  143. continue
  144. if p_entity.entity_type=="location" and p_entity.entity_text==_match["entity_text"]:
  145. find_flag = True
  146. p_entity.entity_type = "company"
  147. if p_entity.entity_type not in ["location","org","company"]:
  148. continue
  149. #有重叠
  150. #match部分被包含则不处理
  151. if _match["begin_index"]>=p_entity.wordOffset_begin and _match["end_index"]<=p_entity.wordOffset_end:
  152. find_flag = True
  153. #判断是否是多个公司
  154. for _match_j in range(_match_index,len(list_match)):
  155. if not list_match[_match_j]["end_index"]<=p_entity.wordOffset_end:
  156. _match_j -= 1
  157. break
  158. if _match_j>_match_index:
  159. match_replace = True
  160. match_add = True
  161. begin_index = changeIndexFromWordToWords(tokens,_match["begin_index"])
  162. end_index = changeIndexFromWordToWords(tokens,_match["end_index"])
  163. list_calibrate.append({"type":"update","from":p_entity.entity_text,"to":_match["entity_text"]})
  164. p_entity.entity_text = _match["entity_text"]
  165. p_entity.wordOffset_begin = _match["begin_index"]
  166. p_entity.wordOffset_end = _match["end_index"]
  167. p_entity.begin_index = begin_index
  168. p_entity.end_index = end_index
  169. for _match_h in range(_match_index+1,_match_j+1):
  170. entity_text = list_match[_match_h]["entity_text"]
  171. entity_type = "company"
  172. begin_index = changeIndexFromWordToWords(tokens,list_match[_match_h]["begin_index"])
  173. end_index = changeIndexFromWordToWords(tokens,list_match[_match_h]["end_index"])
  174. entity_id = "%s_%d_%d_%d"%(doc_id,sentence_index,begin_index,end_index)
  175. add_entity = Entity(p_sentence.doc_id,entity_id,entity_text,entity_type,sentence_index,begin_index,end_index,list_match[_match_h]["begin_index"],list_match[_match_h]["end_index"])
  176. list_entity.append(add_entity)
  177. range_entity.append(add_entity)
  178. list_calibrate.append({"type":"add","from":"","to":entity_text})
  179. _match_index = _match_j
  180. break
  181. continue
  182. elif _match["begin_index"]<=p_entity.wordOffset_begin and _match["end_index"]>p_entity.wordOffset_begin:
  183. find_flag = True
  184. if _match["begin_index"]<p_entity.wordOffset_begin and _match["end_index"]<=p_entity.wordOffset_end:
  185. if p_entity.entity_type in ("org","company"):
  186. _diff_text = sentence[p_entity.wordOffset_end:_match["end_index"]]
  187. if re.search("分",_diff_text) is not None:
  188. pass
  189. else:
  190. match_replace = True
  191. begin_index = changeIndexFromWordToWords(tokens,_match["begin_index"])
  192. end_index = changeIndexFromWordToWords(tokens,_match["end_index"])
  193. list_calibrate.append({"type":"update","from":p_entity.entity_text,"to":_match["entity_text"]})
  194. p_entity.entity_text = _match["entity_text"]
  195. p_entity.wordOffset_begin = _match["begin_index"]
  196. p_entity.wordOffset_end = _match["end_index"]
  197. p_entity.begin_index = begin_index
  198. p_entity.end_index = end_index
  199. elif _match["end_index"]>=p_entity.wordOffset_end:
  200. match_replace = True
  201. begin_index = changeIndexFromWordToWords(tokens,_match["begin_index"])
  202. end_index = changeIndexFromWordToWords(tokens,_match["end_index"])
  203. list_calibrate.append({"type":"update","from":p_entity.entity_text,"to":_match["entity_text"]})
  204. p_entity.entity_text = _match["entity_text"]
  205. p_entity.wordOffset_begin = _match["begin_index"]
  206. p_entity.wordOffset_end = _match["end_index"]
  207. p_entity.begin_index = begin_index
  208. p_entity.end_index = end_index
  209. p_entity.entity_type = "company"
  210. elif _match["begin_index"]<p_entity.wordOffset_end and _match["end_index"]>p_entity.wordOffset_end:
  211. find_flag = True
  212. if p_entity.entity_type in ("org","company"):
  213. match_replace = True
  214. begin_index = changeIndexFromWordToWords(tokens,_match["begin_index"])
  215. end_index = changeIndexFromWordToWords(tokens,_match["end_index"])
  216. list_calibrate.append({"type":"update","from":p_entity.entity_text,"to":_match["entity_text"]})
  217. p_entity.entity_text = _match["entity_text"]
  218. p_entity.wordOffset_begin = _match["begin_index"]
  219. p_entity.wordOffset_end = _match["end_index"]
  220. p_entity.begin_index = begin_index
  221. p_entity.end_index = end_index
  222. if not find_flag:
  223. match_add = True
  224. entity_text = _match["entity_text"]
  225. entity_type = "company"
  226. begin_index = changeIndexFromWordToWords(tokens,_match["begin_index"])
  227. end_index = changeIndexFromWordToWords(tokens,_match["end_index"])
  228. entity_id = "%s_%d_%d_%d"%(doc_id,sentence_index,begin_index,end_index)
  229. add_entity = Entity(p_sentence.doc_id,entity_id,entity_text,entity_type,sentence_index,begin_index,end_index,_match["begin_index"],_match["end_index"])
  230. list_entity.append(add_entity)
  231. range_entity.append(add_entity)
  232. list_calibrate.append({"type":"add","from":"","to":entity_text})
  233. #去重
  234. set_calibrate = set()
  235. list_match_enterprise = []
  236. for _calibrate in list_calibrate:
  237. _from = _calibrate.get("from","")
  238. _to = _calibrate.get("to","")
  239. _key = _from+_to
  240. if _key not in set_calibrate:
  241. list_match_enterprise.append(_calibrate)
  242. set_calibrate.add(_key)
  243. match_enterprise_type = 0
  244. if match_add:
  245. match_enterprise_type += 1
  246. if match_replace:
  247. match_enterprise_type += 2
  248. _article.match_enterprise = list_match_enterprise
  249. _article.match_enterprise_type = match_enterprise_type
  250. def isLegalEnterprise(name):
  251. is_legal = True
  252. if re.search("^[省市区县]",name) is not None or re.search("^.{,3}(分(公司|行|支)|街道|中心|办事处|经营部)$",name) or re.search("标段|标包|名称",name) is not None:
  253. is_legal = False
  254. return is_legal
  255. def fix_LEGAL_ENTERPRISE():
  256. unlegal_enterprise = []
  257. _path = getEnterprisePath()
  258. _sum = 0
  259. with open("enter.txt","w",encoding="utf8") as fwrite:
  260. fwrite.write("大理市方向电脑经营部\n")
  261. with open(_path,"r",encoding="utf8") as f:
  262. while True:
  263. line = f.readline()
  264. if not line:
  265. break
  266. _sum += 1
  267. line = line.strip()
  268. if isLegalEnterprise(line):
  269. fwrite.write(line.replace("(","(").replace(")",")"))
  270. fwrite.write("\n")
  271. # if re.search("标段|地址|标包|名称",line) is not None:#\(|\)||
  272. # _count += 1
  273. # print("=",line)
  274. # print("%d/%d"%(_count,_sum))
  275. if __name__=="__main__":
  276. # edit_distance("GUMBO","GAMBOL")
  277. # print(jaccard_score("周口经济开发区陈营运粮河两岸拆迁工地土工布覆盖项目竞争性谈判公告","周口经济开发区陈营运粮河两岸拆迁工地土工布覆盖项目-成交公告"))
  278. #
  279. # sentences = "广州比地数据科技有限公司比地数据科技有限公司1111111123沈阳南光工贸有限公司"
  280. # print(match_enterprise_max_first(sentences))
  281. #
  282. # print("takes %d s"%(time.time()-_time))
  283. fix_LEGAL_ENTERPRISE()