entityLink.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  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. _score = jaccard_score(_entity.entity_text, _ent.entity_text)
  45. if _entity.entity_text!=_ent.entity_text and _score>=on_value:
  46. _entity.linked_entitys.append(_ent)
  47. _ent.linked_entitys.append(_entity)
  48. #替换公司名称
  49. for _entity in range_entity:
  50. if re.search("公司",_entity.entity_text) is None:
  51. for _ent in _entity.linked_entitys:
  52. if re.search("公司$",_ent.entity_text) is not None:
  53. if len(_ent.entity_text)>len(_entity.entity_text):
  54. _entity.entity_text = _ent.entity_text
  55. def getEnterprisePath():
  56. filename = "LEGAL_ENTERPRISE.txt"
  57. filepath = os.path.dirname(__file__)+"/../"
  58. real_path = filename
  59. if os.path.exists(filepath+filename):
  60. real_path = filepath+filename
  61. return real_path
  62. DICT_ENTERPRISE = {}
  63. DICT_ENTERPRISE_DONE = False
  64. def getDict_enterprise():
  65. global DICT_ENTERPRISE,DICT_ENTERPRISE_DONE
  66. real_path = getEnterprisePath()
  67. with open(real_path,"r",encoding="UTF8") as f:
  68. for _e in f:
  69. if not _e:
  70. continue
  71. _e = _e.strip()
  72. if len(_e)>=4:
  73. key_enter = _e[:4]
  74. if key_enter not in DICT_ENTERPRISE:
  75. DICT_ENTERPRISE[key_enter] = set()
  76. DICT_ENTERPRISE[key_enter].add(_e[4:])
  77. # for _e in ["河南省柘源","建筑工程有限公司"]:
  78. # if not _e:
  79. # continue
  80. # _e = _e.strip()
  81. # if len(_e)>=4:
  82. # key_enter = _e[:4]
  83. # if key_enter not in DICT_ENTERPRISE:
  84. # DICT_ENTERPRISE[key_enter] = set()
  85. # DICT_ENTERPRISE[key_enter].add(_e[4:])
  86. DICT_ENTERPRISE_DONE = True
  87. return DICT_ENTERPRISE
  88. import threading
  89. import time
  90. load_enterprise_thread = threading.Thread(target=getDict_enterprise)
  91. load_enterprise_thread.start()
  92. MAX_ENTERPRISE_LEN = 30
  93. def match_enterprise_max_first(sentence):
  94. while True:
  95. if not DICT_ENTERPRISE_DONE:
  96. time.sleep(1)
  97. else:
  98. break
  99. list_match = []
  100. begin_index = 0
  101. if len(sentence)>4:
  102. while True:
  103. if begin_index+4<len(sentence):
  104. key_enter = sentence[begin_index:begin_index+4]
  105. if key_enter in DICT_ENTERPRISE:
  106. for _i in range(MAX_ENTERPRISE_LEN-4+1):
  107. enter_name = sentence[begin_index+4:begin_index+MAX_ENTERPRISE_LEN-_i]
  108. if enter_name in DICT_ENTERPRISE[key_enter]:
  109. match_item = {"entity_text":"%s%s"%(key_enter,enter_name),"begin_index":begin_index,"end_index":begin_index+len(key_enter)+len(enter_name)}
  110. list_match.append(match_item)
  111. begin_index += (len(key_enter)+len(enter_name))-1
  112. break
  113. begin_index += 1
  114. else:
  115. break
  116. return list_match
  117. def calibrateEnterprise(list_articles,list_sentences,list_entitys):
  118. for _article,list_sentence,list_entity in zip(list_articles,list_sentences,list_entitys):
  119. list_calibrate = []
  120. match_add = False
  121. match_replace = False
  122. range_entity = []
  123. for p_entity in list_entity:
  124. if p_entity.entity_type in ("org","company","location"):
  125. range_entity.append(p_entity)
  126. if len(range_entity)>1000:
  127. break
  128. for p_sentence in list_sentence:
  129. sentence = p_sentence.sentence_text
  130. list_match = match_enterprise_max_first(sentence)
  131. doc_id = p_sentence.doc_id
  132. sentence_index = p_sentence.sentence_index
  133. tokens = p_sentence.tokens
  134. list_match.sort(key=lambda x:x["begin_index"])
  135. for _match_index in range(len(list_match)):
  136. _match = list_match[_match_index]
  137. find_flag = False
  138. for p_entity in range_entity:
  139. if p_entity.sentence_index!=p_sentence.sentence_index:
  140. continue
  141. if p_entity.entity_type=="location" and p_entity.entity_text==_match["entity_text"]:
  142. find_flag = True
  143. p_entity.entity_type = "company"
  144. #有重叠
  145. #match部分被包含则不处理
  146. if _match["begin_index"]>=p_entity.wordOffset_begin and _match["end_index"]<=p_entity.wordOffset_end:
  147. find_flag = True
  148. #判断是否是多个公司
  149. for _match_j in range(_match_index,len(list_match)):
  150. if not list_match[_match_j]["end_index"]<=p_entity.wordOffset_end:
  151. _match_j -= 1
  152. break
  153. if _match_j>_match_index:
  154. match_replace = True
  155. match_add = True
  156. begin_index = changeIndexFromWordToWords(tokens,_match["begin_index"])
  157. end_index = changeIndexFromWordToWords(tokens,_match["end_index"])
  158. list_calibrate.append({"type":"update","from":p_entity.entity_text,"to":_match["entity_text"]})
  159. p_entity.entity_text = _match["entity_text"]
  160. p_entity.wordOffset_begin = _match["begin_index"]
  161. p_entity.wordOffset_end = _match["end_index"]
  162. p_entity.begin_index = begin_index
  163. p_entity.end_index = end_index
  164. for _match_h in range(_match_index+1,_match_j+1):
  165. entity_text = list_match[_match_h]["entity_text"]
  166. entity_type = "company"
  167. begin_index = changeIndexFromWordToWords(tokens,list_match[_match_h]["begin_index"])
  168. end_index = changeIndexFromWordToWords(tokens,list_match[_match_h]["end_index"])
  169. entity_id = "%s_%d_%d_%d"%(doc_id,sentence_index,begin_index,end_index)
  170. 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"])
  171. list_entity.append(add_entity)
  172. range_entity.append(add_entity)
  173. list_calibrate.append({"type":"add","from":"","to":entity_text})
  174. _match_index = _match_j
  175. break
  176. continue
  177. elif _match["begin_index"]<=p_entity.wordOffset_begin and _match["end_index"]>p_entity.wordOffset_begin:
  178. find_flag = True
  179. if p_entity.entity_type in ("org","company"):
  180. if _match["begin_index"]<p_entity.wordOffset_begin and _match["end_index"]<=p_entity.wordOffset_end:
  181. _diff_text = sentence[p_entity.wordOffset_end:_match["end_index"]]
  182. if re.search("分",_diff_text) is not None:
  183. pass
  184. else:
  185. match_replace = True
  186. begin_index = changeIndexFromWordToWords(tokens,_match["begin_index"])
  187. end_index = changeIndexFromWordToWords(tokens,_match["end_index"])
  188. list_calibrate.append({"type":"update","from":p_entity.entity_text,"to":_match["entity_text"]})
  189. p_entity.entity_text = _match["entity_text"]
  190. p_entity.wordOffset_begin = _match["begin_index"]
  191. p_entity.wordOffset_end = _match["end_index"]
  192. p_entity.begin_index = begin_index
  193. p_entity.end_index = end_index
  194. elif _match["end_index"]>=p_entity.wordOffset_end:
  195. match_replace = True
  196. begin_index = changeIndexFromWordToWords(tokens,_match["begin_index"])
  197. end_index = changeIndexFromWordToWords(tokens,_match["end_index"])
  198. list_calibrate.append({"type":"update","from":p_entity.entity_text,"to":_match["entity_text"]})
  199. p_entity.entity_text = _match["entity_text"]
  200. p_entity.wordOffset_begin = _match["begin_index"]
  201. p_entity.wordOffset_end = _match["end_index"]
  202. p_entity.begin_index = begin_index
  203. p_entity.end_index = end_index
  204. elif _match["begin_index"]<p_entity.wordOffset_end and _match["end_index"]>p_entity.wordOffset_end:
  205. find_flag = True
  206. if p_entity.entity_type in ("org","company"):
  207. match_replace = True
  208. begin_index = changeIndexFromWordToWords(tokens,_match["begin_index"])
  209. end_index = changeIndexFromWordToWords(tokens,_match["end_index"])
  210. list_calibrate.append({"type":"update","from":p_entity.entity_text,"to":_match["entity_text"]})
  211. p_entity.entity_text = _match["entity_text"]
  212. p_entity.wordOffset_begin = _match["begin_index"]
  213. p_entity.wordOffset_end = _match["end_index"]
  214. p_entity.begin_index = begin_index
  215. p_entity.end_index = end_index
  216. if not find_flag:
  217. match_add = True
  218. entity_text = _match["entity_text"]
  219. entity_type = "company"
  220. begin_index = changeIndexFromWordToWords(tokens,_match["begin_index"])
  221. end_index = changeIndexFromWordToWords(tokens,_match["end_index"])
  222. entity_id = "%s_%d_%d_%d"%(doc_id,sentence_index,begin_index,end_index)
  223. 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"])
  224. list_entity.append(add_entity)
  225. range_entity.append(add_entity)
  226. list_calibrate.append({"type":"add","from":"","to":entity_text})
  227. #去重
  228. set_calibrate = set()
  229. list_match_enterprise = []
  230. for _calibrate in list_calibrate:
  231. _from = _calibrate.get("from","")
  232. _to = _calibrate.get("to","")
  233. _key = _from+_to
  234. if _key not in set_calibrate:
  235. list_match_enterprise.append(_calibrate)
  236. set_calibrate.add(_key)
  237. match_enterprise_type = 0
  238. if match_add:
  239. match_enterprise_type += 1
  240. if match_replace:
  241. match_enterprise_type += 2
  242. _article.match_enterprise = list_match_enterprise
  243. _article.match_enterprise_type = match_enterprise_type
  244. if __name__=="__main__":
  245. # edit_distance("GUMBO","GAMBOL")
  246. print(jaccard_score("周口经济开发区陈营运粮河两岸拆迁工地土工布覆盖项目竞争性谈判公告","周口经济开发区陈营运粮河两岸拆迁工地土工布覆盖项目-成交公告"))
  247. sentences = "广州比地数据科技有限公司比地数据科技有限公司1111111123沈阳南光工贸有限公司"
  248. print(match_enterprise_max_first(sentences))
  249. print("takes %d s"%(time.time()-_time))