entityLink.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436
  1. #coding:UTF8
  2. '''
  3. Created on 2019年5月21日
  4. @author: User
  5. '''
  6. import re
  7. import os
  8. import time
  9. import pandas as pd
  10. _time = time.time()
  11. from BiddingKG.dl.common.Utils import *
  12. from BiddingKG.dl.interface.Entitys import *
  13. import json
  14. def edit_distance(source,target):
  15. dp = [["" for i in range(len(source)+1)] for j in range(len(target)+1)]
  16. for i in range(len(dp)):
  17. for j in range(len(dp[i])):
  18. if i==0:
  19. dp[i][j] = j
  20. elif j==0:
  21. dp[i][j] = i
  22. else:
  23. if source[j-1]==target[i-1]:
  24. cost = 0
  25. else:
  26. cost = 2
  27. dp[i][j] = min([dp[i-1][j]+1,dp[i][j-1]+1,dp[i-1][j-1]+cost])
  28. return dp[-1][-1]
  29. def jaccard_score(source,target):
  30. source_set = set([s for s in source])
  31. target_set = set([s for s in target])
  32. if len(source_set)==0 or len(target_set)==0:
  33. return 0
  34. return max(len(source_set&target_set)/len(source_set),len(source_set&target_set)/len(target_set))
  35. def get_place_list():
  36. path = os.path.dirname(__file__) + '/../place_info.csv'
  37. place_df = pd.read_csv(path)
  38. place_list = []
  39. for index, row in place_df.iterrows():
  40. place_list.append(row[1])
  41. place_list.append('台湾')
  42. place_list.append('澳门')
  43. place_list.append('香港')
  44. # place_list.append('東莞')
  45. # place_list.append('廣州')
  46. # place_list.append('韩国')
  47. # place_list.append('德国')
  48. # place_list.append('英国')
  49. # place_list.append('日本')
  50. # place_list.append('意大利')
  51. # place_list.append('新加坡')
  52. # place_list.append('加拿大')
  53. # place_list.append('西班牙')
  54. # place_list.append('澳大利亚')
  55. # place_list.append('美国')
  56. place_list = list(set(place_list))
  57. return place_list
  58. place_list = get_place_list()
  59. place_pattern = "|".join(place_list)
  60. def link_entitys(list_entitys,on_value=0.81):
  61. for list_entity in list_entitys:
  62. range_entity = []
  63. for _entity in list_entity:
  64. if _entity.entity_type in ["org","company"]:
  65. range_entity.append(_entity)
  66. range_entity = range_entity[:1000]
  67. for first_i in range(len(range_entity)):
  68. _entity = range_entity[first_i]
  69. for second_i in range(first_i+1,len(range_entity)):
  70. _ent = range_entity[second_i]
  71. # 2021/5/21 update: 两个实体标签互斥(一个是招标人、一个是代理人)且entity_text不相等时,跳过
  72. if _entity.entity_text != _ent.entity_text and _entity.label != _ent.label and _entity.label in [0,1] and _ent.label in [0, 1]:
  73. continue
  74. _score = jaccard_score(re.sub("%s|%s"%("股份|责任|有限|公司",place_pattern),"",_entity.entity_text), re.sub("%s|%s"%("股份|责任|有限|公司",place_pattern),"",_ent.entity_text))
  75. if _entity.entity_text!=_ent.entity_text and _score>=on_value:
  76. _entity.linked_entitys.append(_ent)
  77. _ent.linked_entitys.append(_entity)
  78. #替换公司名称
  79. for _entity in range_entity:
  80. if re.search("公司",_entity.entity_text) is None:
  81. for _ent in _entity.linked_entitys:
  82. if re.search("公司$",_ent.entity_text) is not None:
  83. if len(_ent.entity_text)>len(_entity.entity_text):
  84. _entity.entity_text = _ent.entity_text
  85. # 2021/12/21 替换通过字典识别到的取长度最大的相似实体
  86. for _entity in range_entity:
  87. used_linked_entitys = []
  88. if not _entity.linked_entitys:
  89. continue
  90. _entity.linked_entitys.sort(key=lambda x: len(x.entity_text), reverse=True)
  91. for _ent in _entity.linked_entitys:
  92. if _ent in used_linked_entitys:
  93. break
  94. # print("_entity, _ent", _entity.entity_text, _ent.if_dict_match, _ent.entity_text)
  95. if _ent.if_dict_match == 1:
  96. if len(_ent.entity_text) > len(_entity.entity_text):
  97. # 判断两个公司地区相同
  98. match_list_1, match_list_2 = [], []
  99. for place in place_list:
  100. if place in _entity.entity_text:
  101. match_list_1.append(place)
  102. if place in _ent.entity_text:
  103. match_list_2.append(place)
  104. if str(match_list_1) == str(match_list_2):
  105. # print("字典替换", _entity.entity_text, "->", _ent.entity_text)
  106. _entity.origin_entity_text = _entity.entity_text
  107. _entity.entity_text = _ent.entity_text
  108. used_linked_entitys.append(_ent)
  109. # print(_entity.entity_text, _entity.if_dict_match, _ent.entity_text, _ent.if_dict_match)
  110. def doctitle_refine(doctitle):
  111. _doctitle_refine = re.sub(r'工程|服务|询价|比价|谈判|竞争性|磋商|结果|中标|招标|采购|的|公示|公开|成交|公告|评标|候选人|'
  112. r'交易|通知|废标|流标|终止|中止|一笔|预告|单一来源|竞价|合同', '', doctitle)
  113. return _doctitle_refine
  114. # 前100个公司实体
  115. def get_nlp_enterprise(list_entity):
  116. count = 0
  117. nlp_enterprise = []
  118. list_entity = sorted(list_entity,key=lambda x:(x.sentence_index,x.begin_index))
  119. for entity in list_entity:
  120. if entity.entity_type in ['org','company']:
  121. if entity.entity_text not in nlp_enterprise:
  122. nlp_enterprise.append(entity.entity_text)
  123. count += 1
  124. if count>=100:
  125. break
  126. return nlp_enterprise
  127. def getEnterprisePath():
  128. filename = "LEGAL_ENTERPRISE.txt"
  129. real_path = getFileFromSysPath(filename)
  130. if real_path is None:
  131. real_path = filename
  132. return real_path
  133. DICT_ENTERPRISE = {}
  134. DICT_ENTERPRISE_DONE = False
  135. def getDict_enterprise():
  136. global DICT_ENTERPRISE,DICT_ENTERPRISE_DONE
  137. real_path = getEnterprisePath()
  138. with open(real_path,"r",encoding="UTF8") as f:
  139. for _e in f:
  140. if not _e:
  141. continue
  142. _e = _e.strip()
  143. if len(_e)>=4:
  144. key_enter = _e[:4]
  145. if key_enter not in DICT_ENTERPRISE:
  146. DICT_ENTERPRISE[key_enter] = set()
  147. DICT_ENTERPRISE[key_enter].add(_e[4:])
  148. # for _e in ["河南省柘源","建筑工程有限公司"]:
  149. # if not _e:
  150. # continue
  151. # _e = _e.strip()
  152. # if len(_e)>=4:
  153. # key_enter = _e[:4]
  154. # if key_enter not in DICT_ENTERPRISE:
  155. # DICT_ENTERPRISE[key_enter] = set()
  156. # DICT_ENTERPRISE[key_enter].add(_e[4:])
  157. DICT_ENTERPRISE_DONE = True
  158. return DICT_ENTERPRISE
  159. import threading
  160. import time
  161. load_enterprise_thread = threading.Thread(target=getDict_enterprise)
  162. load_enterprise_thread.start()
  163. MAX_ENTERPRISE_LEN = 30
  164. def match_enterprise_max_first(sentence):
  165. while True:
  166. if not DICT_ENTERPRISE_DONE:
  167. time.sleep(1)
  168. else:
  169. break
  170. list_match = []
  171. begin_index = 0
  172. if len(sentence)>4:
  173. while True:
  174. if begin_index+4<len(sentence):
  175. key_enter = sentence[begin_index:begin_index+4]
  176. if key_enter in DICT_ENTERPRISE:
  177. for _i in range(MAX_ENTERPRISE_LEN-4+1):
  178. enter_name = sentence[begin_index+4:begin_index+MAX_ENTERPRISE_LEN-_i]
  179. if enter_name in DICT_ENTERPRISE[key_enter]:
  180. match_item = {"entity_text":"%s%s"%(key_enter,enter_name),"begin_index":begin_index,"end_index":begin_index+len(key_enter)+len(enter_name)}
  181. list_match.append(match_item)
  182. begin_index += (len(key_enter)+len(enter_name))-1
  183. break
  184. begin_index += 1
  185. else:
  186. break
  187. return list_match
  188. def calibrateEnterprise(list_articles,list_sentences,list_entitys):
  189. for _article,list_sentence,list_entity in zip(list_articles,list_sentences,list_entitys):
  190. list_calibrate = []
  191. match_add = False
  192. match_replace = False
  193. range_entity = []
  194. for p_entity in list_entity:
  195. if p_entity.entity_type in ("org","company","location"):
  196. range_entity.append(p_entity)
  197. if len(range_entity)>1000:
  198. break
  199. for p_sentence in list_sentence:
  200. sentence = p_sentence.sentence_text
  201. sentence_entitys = [(ent.entity_text,ent.wordOffset_begin,ent.wordOffset_end) for ent in list_entity if ent.sentence_index==p_sentence.sentence_index and ent.entity_type in ['org','company']]
  202. list_match = match_enterprise_max_first(sentence)
  203. # print("list_match", list_match)
  204. doc_id = p_sentence.doc_id
  205. sentence_index = p_sentence.sentence_index
  206. tokens = p_sentence.tokens
  207. list_match.sort(key=lambda x:x["begin_index"])
  208. for _match_index in range(len(list_match)):
  209. _match = list_match[_match_index]
  210. find_flag = False
  211. for p_entity in range_entity:
  212. if p_entity.sentence_index!=p_sentence.sentence_index:
  213. continue
  214. if p_entity.entity_type=="location" and p_entity.entity_text==_match["entity_text"]:
  215. find_flag = True
  216. p_entity.entity_type = "company"
  217. p_entity.if_dict_match = 1
  218. if p_entity.entity_type not in ["location","org","company"]:
  219. continue
  220. if _match["entity_text"] == p_entity.entity_text:
  221. p_entity.if_dict_match = 1
  222. #有重叠
  223. #match部分被包含则不处理
  224. if _match["begin_index"]>=p_entity.wordOffset_begin and _match["end_index"]<=p_entity.wordOffset_end:
  225. find_flag = True
  226. #判断是否是多个公司
  227. for _match_j in range(_match_index,len(list_match)):
  228. if not list_match[_match_j]["end_index"]<=p_entity.wordOffset_end:
  229. _match_j -= 1
  230. break
  231. if _match_j>_match_index:
  232. match_replace = True
  233. match_add = True
  234. begin_index = changeIndexFromWordToWords(tokens,_match["begin_index"])
  235. end_index = changeIndexFromWordToWords(tokens,_match["end_index"]-1)
  236. list_calibrate.append({"type":"update","from":p_entity.entity_text,"to":_match["entity_text"]})
  237. p_entity.entity_text = _match["entity_text"]
  238. p_entity.wordOffset_begin = _match["begin_index"]
  239. p_entity.wordOffset_end = _match["end_index"]
  240. p_entity.begin_index = begin_index
  241. p_entity.end_index = end_index
  242. # 该公司实体是字典识别的
  243. p_entity.if_dict_match = 1
  244. for _match_h in range(_match_index+1,_match_j+1):
  245. entity_text = list_match[_match_h]["entity_text"]
  246. entity_type = "company"
  247. begin_index = changeIndexFromWordToWords(tokens,list_match[_match_h]["begin_index"])
  248. end_index = changeIndexFromWordToWords(tokens,list_match[_match_h]["end_index"]-1)
  249. entity_id = "%s_%d_%d_%d"%(doc_id,sentence_index,begin_index,end_index)
  250. 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"],in_attachment=p_sentence.in_attachment)
  251. add_entity.if_dict_match = 1
  252. list_entity.append(add_entity)
  253. range_entity.append(add_entity)
  254. list_calibrate.append({"type":"add","from":"","to":entity_text})
  255. _match_index = _match_j
  256. break
  257. continue
  258. elif _match["begin_index"]<=p_entity.wordOffset_begin and _match["end_index"]>p_entity.wordOffset_begin:
  259. find_flag = True
  260. if _match["begin_index"]<p_entity.wordOffset_begin and _match["end_index"]<=p_entity.wordOffset_end:
  261. if p_entity.entity_type in ("org","company"):
  262. _diff_text = sentence[p_entity.wordOffset_end:_match["end_index"]]
  263. if re.search("分",_diff_text) is not None:
  264. pass
  265. else:
  266. match_replace = True
  267. begin_index = changeIndexFromWordToWords(tokens,_match["begin_index"])
  268. end_index = changeIndexFromWordToWords(tokens,_match["end_index"]-1)
  269. list_calibrate.append({"type":"update","from":p_entity.entity_text,"to":_match["entity_text"]})
  270. p_entity.entity_text = _match["entity_text"]
  271. p_entity.wordOffset_begin = _match["begin_index"]
  272. p_entity.wordOffset_end = _match["end_index"]
  273. p_entity.begin_index = begin_index
  274. p_entity.end_index = end_index
  275. p_entity.if_dict_match = 1
  276. elif _match["end_index"]>=p_entity.wordOffset_end:
  277. # 原entity列表已有实体,则不重复添加
  278. if (_match["entity_text"],_match["begin_index"],_match["end_index"]) not in sentence_entitys:
  279. match_replace = True
  280. begin_index = changeIndexFromWordToWords(tokens,_match["begin_index"])
  281. end_index = changeIndexFromWordToWords(tokens,_match["end_index"]-1)
  282. list_calibrate.append({"type":"update","from":p_entity.entity_text,"to":_match["entity_text"]})
  283. p_entity.entity_text = _match["entity_text"]
  284. p_entity.wordOffset_begin = _match["begin_index"]
  285. p_entity.wordOffset_end = _match["end_index"]
  286. p_entity.begin_index = begin_index
  287. p_entity.end_index = end_index
  288. p_entity.entity_type = "company"
  289. p_entity.if_dict_match = 1
  290. elif _match["begin_index"]<p_entity.wordOffset_end and _match["end_index"]>p_entity.wordOffset_end:
  291. find_flag = True
  292. if p_entity.entity_type in ("org","company"):
  293. match_replace = True
  294. begin_index = changeIndexFromWordToWords(tokens,_match["begin_index"])
  295. end_index = changeIndexFromWordToWords(tokens,_match["end_index"]-1)
  296. list_calibrate.append({"type":"update","from":p_entity.entity_text,"to":_match["entity_text"]})
  297. p_entity.entity_text = _match["entity_text"]
  298. p_entity.wordOffset_begin = _match["begin_index"]
  299. p_entity.wordOffset_end = _match["end_index"]
  300. p_entity.begin_index = begin_index
  301. p_entity.end_index = end_index
  302. p_entity.if_dict_match = 1
  303. if not find_flag:
  304. match_add = True
  305. entity_text = _match["entity_text"]
  306. entity_type = "company"
  307. begin_index = changeIndexFromWordToWords(tokens,_match["begin_index"])
  308. end_index = changeIndexFromWordToWords(tokens,_match["end_index"]-1)
  309. entity_id = "%s_%d_%d_%d"%(doc_id,sentence_index,begin_index,end_index)
  310. 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"],in_attachment=p_sentence.in_attachment)
  311. list_entity.append(add_entity)
  312. range_entity.append(add_entity)
  313. list_calibrate.append({"type":"add","from":"","to":entity_text})
  314. #去重
  315. set_calibrate = set()
  316. list_match_enterprise = []
  317. for _calibrate in list_calibrate:
  318. _from = _calibrate.get("from","")
  319. _to = _calibrate.get("to","")
  320. _key = _from+_to
  321. if _key not in set_calibrate:
  322. list_match_enterprise.append(_calibrate)
  323. set_calibrate.add(_key)
  324. match_enterprise_type = 0
  325. if match_add:
  326. match_enterprise_type += 1
  327. if match_replace:
  328. match_enterprise_type += 2
  329. _article.match_enterprise = list_match_enterprise
  330. _article.match_enterprise_type = match_enterprise_type
  331. def isLegalEnterprise(name):
  332. is_legal = True
  333. if re.search("^[省市区县]",name) is not None or re.search("^\**.{,3}(分(公司|行|支)|街道|中心|办事处|经营部|委员会|有限公司)$",name) or re.search("标段|标包|名称",name) is not None:
  334. is_legal = False
  335. print("is_legal:", name , is_legal)
  336. return is_legal
  337. def fix_LEGAL_ENTERPRISE():
  338. unlegal_enterprise = []
  339. _path = getEnterprisePath()
  340. _sum = 0
  341. set_enter = set()
  342. paths = [_path]
  343. for _p in paths:
  344. with open(_p,"r",encoding="utf8") as f:
  345. while True:
  346. line = f.readline()
  347. if not line:
  348. break
  349. line = line.strip()
  350. if isLegalEnterprise(line):
  351. set_enter.add(line)
  352. if line=="有限责任公司" or line=='设计研究院' or line=='限责任公司' or (re.search("^.{,4}(分公司|支行|分行)$",line) is not None and re.search("电信|移动|联通|建行|工行|农行|中行|交行",line) is None):
  353. print(line)
  354. if line in set_enter:
  355. set_enter.remove(line)
  356. with open("enter.txt","w",encoding="utf8") as fwrite:
  357. for line in list(set_enter):
  358. fwrite.write(line.replace("(","(").replace(")",")"))
  359. fwrite.write("\n")
  360. # if re.search("标段|地址|标包|名称",line) is not None:#\(|\)||
  361. # _count += 1
  362. # print("=",line)
  363. # print("%d/%d"%(_count,_sum))
  364. # a_list = []
  365. # with open("电信分公司.txt","r",encoding="utf8") as f:
  366. # while True:
  367. # _line = f.readline()
  368. # if not _line:
  369. # break
  370. # if _line.strip()!="":
  371. # a_list.append(_line.strip())
  372. # with open("enter.txt","a",encoding="utf8") as f:
  373. # for _line in a_list:
  374. # f.write(_line)
  375. # f.write("\n")
  376. if __name__=="__main__":
  377. # edit_distance("GUMBO","GAMBOL")
  378. # print(jaccard_score("周口经济开发区陈营运粮河两岸拆迁工地土工布覆盖项目竞争性谈判公告","周口经济开发区陈营运粮河两岸拆迁工地土工布覆盖项目-成交公告"))
  379. #
  380. # sentences = "广州比地数据科技有限公司比地数据科技有限公司1111111123沈阳南光工贸有限公司"
  381. # print(match_enterprise_max_first(sentences))
  382. #
  383. # print("takes %d s"%(time.time()-_time))
  384. fix_LEGAL_ENTERPRISE()
  385. # print(jaccard_score("中国南方航空股份有限公司上海分公司","南方航空上海分公司"))
  386. # print(match_enterprise_max_first("中国南方航空股份有限公司黑龙江分公司"))