entityLink.py 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775
  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. from BiddingKG.dl.common.constDict import ConstDict
  15. def edit_distance(source,target):
  16. dp = [["" for i in range(len(source)+1)] for j in range(len(target)+1)]
  17. for i in range(len(dp)):
  18. for j in range(len(dp[i])):
  19. if i==0:
  20. dp[i][j] = j
  21. elif j==0:
  22. dp[i][j] = i
  23. else:
  24. if source[j-1]==target[i-1]:
  25. cost = 0
  26. else:
  27. cost = 2
  28. dp[i][j] = min([dp[i-1][j]+1,dp[i][j-1]+1,dp[i-1][j-1]+cost])
  29. return dp[-1][-1]
  30. def jaccard_score(source,target):
  31. source_set = set([s for s in source])
  32. target_set = set([s for s in target])
  33. if len(source_set)==0 or len(target_set)==0:
  34. return 0
  35. return max(len(source_set&target_set)/len(source_set),len(source_set&target_set)/len(target_set))
  36. def get_place_list():
  37. path = os.path.dirname(__file__) + '/../place_info.csv'
  38. place_df = pd.read_csv(path)
  39. place_list = []
  40. for index, row in place_df.iterrows():
  41. place_list.append(row[1])
  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.append('美国')
  57. place_list = list(set(place_list))
  58. return place_list
  59. place_list = get_place_list()
  60. place_pattern = "|".join(place_list)
  61. def is_short(shorter_cut, longer):
  62. '''
  63. 判断是否为简称
  64. :param shorter_cut: 简称
  65. :param longer: 全称
  66. :return:
  67. '''
  68. flag = 1
  69. for words in shorter_cut:
  70. if words in longer:
  71. longer = longer[longer.find(words) + len(words):]
  72. else:
  73. flag = 0
  74. break
  75. if flag:
  76. return 1
  77. else:
  78. return 0
  79. def get_business_data(enterprise_name):
  80. '''
  81. 获取指定公司名称是否有工商数据,有就返回True及相关招投标数据,没有返回False及{}
  82. :param enterprise_name: 公司名称
  83. :return:
  84. '''
  85. global ENTERPRISE_HUGE,SET_ENTERPRISE,POOL_REDIS
  86. # print("test",enterprise_name)
  87. if ENTERPRISE_HUGE:
  88. if POOL_REDIS is None:
  89. init_redis_pool()
  90. _db = POOL_REDIS.getConnector()
  91. try:
  92. _time = time.time()
  93. _v = _db.get(enterprise_name)
  94. POOL_REDIS.putConnector(_db)
  95. if _v is None:
  96. return False, {}
  97. else:
  98. _v = str(_v, 'utf-8')
  99. if 'have_business' in _v:
  100. # log("redis take %.5f of '%s' exists"%(time.time()-_time,enterprise_name))
  101. d = json.loads(_v)
  102. if d.get('have_business', '') == 1:
  103. return True, d
  104. return False, d
  105. else:
  106. return False, {}
  107. except Exception as e:
  108. traceback.print_exc()
  109. return False, {}
  110. else:
  111. if enterprise_name in SET_ENTERPRISE:
  112. return True, {}
  113. else:
  114. return False, {}
  115. def get_role(dic):
  116. '''
  117. 通过字典统计 招标、代理、中标公告数量 返回最大比例及对应类别
  118. :param dic: redics 获取实体的工商数据字典
  119. :return:
  120. '''
  121. if 'zhao_biao_number' in dic:
  122. zhaobiao = dic.get('zhao_biao_number', 0)
  123. daili = dic.get('dai_li_number', 0)
  124. zhongbiao = dic.get('zhong_biao_number', 0)
  125. bid = zhaobiao+ daili+ zhongbiao
  126. if bid > 100: # 总数大于100的才统计
  127. if zhaobiao>=daili:
  128. if zhaobiao>=zhongbiao:
  129. return 0, zhaobiao/bid
  130. else:
  131. return 2, zhongbiao/bid
  132. elif daili >= zhongbiao:
  133. return 1, daili/bid
  134. else:
  135. return 2, zhongbiao/bid
  136. return 5, 0
  137. def link_entitys(list_entitys,on_value=1):#on_value=0.81
  138. for list_entity in list_entitys:
  139. range_entity = []
  140. short_entity = [] # 不包含工商数据实体
  141. long_entity = [] # 包含工商数据实体
  142. n = 0
  143. bus_dic = {} # 保存已查询包含工商数据实体 属于招标、代理、中标 何种类别及对应概率
  144. find_tenderee = False
  145. bus_tenderee = []
  146. for _entity in list_entity:
  147. if _entity.entity_type in ["org","company"]:
  148. ser = re.search('(?P<name>.{2,}(医院|大学|公司))(招[投议]?标|采购)(中心|办公室)$', _entity.entity_text) # 2024-06-07 规范单位名称,去除非必要字眼
  149. if ser:
  150. _entity.entity_text = ser.group('name')
  151. range_entity.append(_entity)
  152. if _entity.entity_text in bus_dic:
  153. have_bus = True
  154. else:
  155. have_bus, dic = get_business_data(_entity.entity_text)
  156. if re.search('^\w{,5}[分支](行|公司)$|^\w{1,3}公司$|^\w{2,5}段$', _entity.entity_text):
  157. have_bus = False
  158. if have_bus:
  159. lb, prob = get_role(dic)
  160. bus_dic[_entity.entity_text] = (lb, prob)
  161. if lb == 0 and prob > 0.9 and re.search('医院|学院|学校|中学|小学|大学|中心|幼儿园|保健院|党校|银行|研究院|血站|分校|红十字会|防治院|研究所', _entity.entity_text) and _entity.entity_text not in ['中华人民共和国', '营业执照', '人民法院','民办非企业单位','个体工商户','运输服务', '社会团体']:
  162. bus_tenderee.append(_entity)
  163. elif re.search('^\w{2,6}银行\w{2,10}[分支]行$', _entity.entity_text): # 2024/05/22 补充某些支行没收集到工商数据
  164. have_bus = True
  165. bus_dic[_entity.entity_text] = (0, 0.5)
  166. if have_bus: # 20231115 改为只判断是否有工商数据,没有就考虑替换
  167. long_entity.append(_entity)
  168. if len(_entity.entity_text)< 6 and re.search('(大学|医院)', _entity.entity_text) == None:
  169. short_entity.append(_entity)
  170. lb, prob = bus_dic[_entity.entity_text]
  171. if lb in [0,1] and prob>0.9 and _entity.label in [0, 1] and _entity.values[_entity.label]<0.55: # 如果工商统计概率较高,文中概率较低,换为统计类别,主要为标题及发布人等招标、代理划分不明确情况
  172. if _entity.label != lb:
  173. _entity.label = lb
  174. _entity.values[_entity.label] = 0.55
  175. else:
  176. _entity.values[_entity.label] += 0.05
  177. else:
  178. short_entity.append(_entity)
  179. if _entity.label == 0: # 找到招标人
  180. find_tenderee = True
  181. n += 1
  182. if n > 1000:
  183. break
  184. if find_tenderee == False and len(bus_tenderee)==1 and bus_tenderee[0].label==5: # 如果整篇都没招标人,工商统计只有一个高概率招标人把它作为招标人
  185. bus_tenderee[0].label = 0
  186. bus_tenderee[0].values[0] = 0.55
  187. range_entity = range_entity[:1000]
  188. #替换公司的逻辑有问题,先取消
  189. # for first_i in range(len(range_entity)):
  190. # _entity = range_entity[first_i]
  191. # for second_i in range(first_i+1,len(range_entity)):
  192. # _ent = range_entity[second_i]
  193. # # 2021/5/21 update: 两个实体标签互斥(一个是招标人、一个是代理人)且entity_text不相等时,跳过
  194. # if _entity.entity_text != _ent.entity_text and _entity.label != _ent.label and _entity.label in [0,1] and _ent.label in [0, 1]:
  195. # continue
  196. # _score = jaccard_score(re.sub("%s|%s"%("股份|责任|有限|公司",place_pattern),"",_entity.entity_text), re.sub("%s|%s"%("股份|责任|有限|公司",place_pattern),"",_ent.entity_text))
  197. # if _entity.entity_text!=_ent.entity_text and _score>=on_value:
  198. # _entity.linked_entitys.append(_ent)
  199. # _ent.linked_entitys.append(_entity)
  200. # print("=-===",_entity.entity_text,_ent.entity_text,_score)
  201. # #替换公司名称
  202. # for _entity in range_entity:
  203. # if re.search("公司",_entity.entity_text) is None:
  204. # for _ent in _entity.linked_entitys:
  205. # if re.search("公司$",_ent.entity_text) is not None:
  206. # if len(_ent.entity_text)>len(_entity.entity_text):
  207. # _entity.entity_text = _ent.entity_text
  208. if short_entity and long_entity: #
  209. for first_i in range(len(short_entity)):
  210. _entity = short_entity[first_i]
  211. if _entity.label == 0:
  212. for second_i in range(len(long_entity)):
  213. _ent = long_entity[second_i]
  214. if _ent.label in [0,1,5]:
  215. if len(_entity.entity_text)<len(_ent.entity_text) and is_short(_entity.entity_text, _ent.entity_text): # 简称顺序包含在工商名称内的替换
  216. _entity.entity_text = _ent.entity_text
  217. lb, prob = bus_dic[_entity.entity_text]
  218. if lb in [0, 1] and prob > 0.9 and _entity.values[
  219. _entity.label] < 0.55: # 如果工商统计概率较高,文中概率较低,换为统计类别,主要为标题及发布人等招标、代理划分不明确情况
  220. if _entity.label != lb:
  221. _entity.label = lb
  222. _entity.values[_entity.label] = 0.55
  223. else:
  224. _entity.values[_entity.label] += 0.05
  225. break
  226. elif len(_entity.entity_text)>len(_ent.entity_text) and _ent.entity_text in _entity.entity_text \
  227. and re.search('(医院|大学)$', _ent.entity_text) and re.search('[部处室科]$', _entity.entity_text): # 不包含工商数据实体完全包含工商数据实体名称的替换 20240520调整限定部门结尾才替换,防止出错
  228. _entity.entity_text = _ent.entity_text
  229. lb, prob = bus_dic[_entity.entity_text]
  230. if lb in [0, 1] and prob > 0.9 and _entity.values[
  231. _entity.label] < 0.55: # 如果工商统计概率较高,文中概率较低,换为统计类别,主要为标题及发布人等招标、代理划分不明确情况
  232. if _entity.label != lb:
  233. _entity.label = lb
  234. _entity.values[_entity.label] = 0.55
  235. else:
  236. _entity.values[_entity.label] += 0.05
  237. break
  238. # 2021/12/21 替换通过字典识别到的取长度最大的相似实体
  239. for _entity in range_entity:
  240. used_linked_entitys = []
  241. if not _entity.linked_entitys:
  242. continue
  243. _entity.linked_entitys.sort(key=lambda x: len(x.entity_text), reverse=True)
  244. for _ent in _entity.linked_entitys:
  245. if _ent in used_linked_entitys:
  246. break
  247. # print("_entity, _ent", _entity.entity_text, _ent.if_dict_match, _ent.entity_text)
  248. if _ent.if_dict_match == 1:
  249. if len(_ent.entity_text) > len(_entity.entity_text):
  250. # 判断两个公司地区相同
  251. match_list_1, match_list_2 = [], []
  252. for place in place_list:
  253. if place in _entity.entity_text:
  254. match_list_1.append(place)
  255. if place in _ent.entity_text:
  256. match_list_2.append(place)
  257. if str(match_list_1) == str(match_list_2):
  258. # print("字典替换", _entity.entity_text, "->", _ent.entity_text)
  259. _entity.origin_entity_text = _entity.entity_text
  260. _entity.entity_text = _ent.entity_text
  261. used_linked_entitys.append(_ent)
  262. # print(_entity.entity_text, _entity.if_dict_match, _ent.entity_text, _ent.if_dict_match)
  263. # 用于去重的标题
  264. def doctitle_refine(doctitle):
  265. _doctitle_refine = re.sub(r'工程|服务|询价|比价|谈判|竞争性|磋商|结果|中标|招标|采购|的|公示|公开|成交|公告|评标|候选人|'
  266. r'交易|通知|废标|流标|终止|中止|一笔|预告|单一来源|竞价|合同', '', doctitle)
  267. return _doctitle_refine
  268. # 前100个公司实体
  269. def get_nlp_enterprise(list_entity):
  270. nlp_enterprise = []
  271. nlp_enterprise_attachment = []
  272. max_num = 100
  273. list_entity = sorted(list_entity,key=lambda x:(x.sentence_index,x.begin_index))
  274. for entity in list_entity:
  275. if entity.entity_type in ['org','company']:
  276. if not entity.in_attachment:
  277. if entity.entity_text not in nlp_enterprise:
  278. nlp_enterprise.append(entity.entity_text)
  279. else:
  280. if entity.entity_text not in nlp_enterprise_attachment:
  281. nlp_enterprise_attachment.append(entity.entity_text)
  282. return nlp_enterprise[:max_num],nlp_enterprise_attachment[:max_num]
  283. ENTERPRISE_HUGE = None
  284. def getEnterprisePath():
  285. global ENTERPRISE_HUGE
  286. filename_huge = "LEGAL_ENTERPRISE_HUGE.txt"
  287. huge_path = getFileFromSysPath(filename_huge)
  288. if huge_path is None:
  289. if os.path.exists(filename_huge):
  290. log("enterprise path:%s"%(filename_huge))
  291. ENTERPRISE_HUGE = True
  292. return filename_huge,ENTERPRISE_HUGE
  293. else:
  294. log("enterprise path:%s"%(huge_path))
  295. ENTERPRISE_HUGE = True
  296. return huge_path,ENTERPRISE_HUGE
  297. filename = "LEGAL_ENTERPRISE.txt"
  298. real_path = getFileFromSysPath(filename)
  299. if real_path is None:
  300. real_path = filename
  301. log("ENTERPRISE path:%s"%(real_path))
  302. ENTERPRISE_HUGE = False
  303. return real_path,ENTERPRISE_HUGE
  304. DICT_ENTERPRISE_DONE = False
  305. POOL_REDIS = None
  306. ENTERPRISE_KEY_LEN = 3
  307. ENTERPRISE_PREFIX_LEN = 3
  308. ENTERPRISE_TAIL_LEN = 3
  309. SET_ENTERPRISE = set()
  310. SET_PREFIX_ENTERPRISE = set()
  311. SET_TAIL_ENTERPRISE = set()
  312. SET_PREFIX_ENTERPRISE_HUGE_FILE = "SET_PREFIX_ENTERPRISE_HUGE.pk"
  313. SET_TAIL_ENTERPRISE_HUGE_FILE = "SET_TAIL_ENTERPRISE_HUGE.pk"
  314. def getDict_enterprise():
  315. global DICT_ENTERPRISE_DONE,SET_ENTERPRISE,SET_PREFIX_ENTERPRISE,SET_TAIL_ENTERPRISE
  316. real_path,is_huge = getEnterprisePath()
  317. _ok = False
  318. if is_huge:
  319. if os.path.exists(SET_PREFIX_ENTERPRISE_HUGE_FILE) and os.path.exists(SET_TAIL_ENTERPRISE_HUGE_FILE):
  320. SET_PREFIX_ENTERPRISE = load(SET_PREFIX_ENTERPRISE_HUGE_FILE)
  321. SET_TAIL_ENTERPRISE = load(SET_TAIL_ENTERPRISE_HUGE_FILE)
  322. _ok = True
  323. if not _ok:
  324. with open(real_path,"r",encoding="UTF8") as f:
  325. for _e in f:
  326. if not _e:
  327. continue
  328. _e = _e.strip()
  329. if len(_e)>=4:
  330. key_enter = _e[:ENTERPRISE_KEY_LEN]
  331. SET_PREFIX_ENTERPRISE.add(key_enter)
  332. SET_TAIL_ENTERPRISE.add(_e[-ENTERPRISE_TAIL_LEN:])
  333. if not is_huge:
  334. SET_ENTERPRISE.add(_e)
  335. #仅在大文件情况下才使用缓存加载
  336. if is_huge:
  337. save(SET_PREFIX_ENTERPRISE,SET_PREFIX_ENTERPRISE_HUGE_FILE)
  338. save(SET_TAIL_ENTERPRISE,SET_TAIL_ENTERPRISE_HUGE_FILE)
  339. log("SET_PREFIX_ENTERPRISE takes memory:%.2fM size:%d"%(sys.getsizeof(SET_PREFIX_ENTERPRISE)/1024/1024,len(SET_PREFIX_ENTERPRISE)))
  340. log("SET_TAIL_ENTERPRISE takes memory:%.2fM size:%d"%(sys.getsizeof(SET_TAIL_ENTERPRISE)/1024/1024,len(SET_TAIL_ENTERPRISE)))
  341. log("SET_ENTERPRISE takes memory:%.2fM size:%d"%(sys.getsizeof(SET_ENTERPRISE)/1024/1024,len(SET_ENTERPRISE)))
  342. # for _e in ["河南省柘源","建筑工程有限公司"]:
  343. # if not _e:
  344. # continue
  345. # _e = _e.strip()
  346. # if len(_e)>=4:
  347. # key_enter = _e[:4]
  348. # if key_enter not in DICT_ENTERPRISE:
  349. # DICT_ENTERPRISE[key_enter] = set()
  350. # DICT_ENTERPRISE[key_enter].add(_e[4:])
  351. DICT_ENTERPRISE_DONE = True
  352. def init_redis_pool():
  353. from BiddingKG.dl.common.pool import ConnectorPool
  354. from BiddingKG.dl.common.source import getConnect_redis_baseline
  355. global POOL_REDIS
  356. if POOL_REDIS is None:
  357. POOL_REDIS = ConnectorPool(init_num=1,max_num=10,method_init=getConnect_redis_baseline)
  358. # 插入 Redis
  359. # def add_redis(company_list):
  360. # global ENTERPRISE_HUGE,POOL_REDIS
  361. # if ENTERPRISE_HUGE:
  362. # _db = POOL_REDIS.getConnector()
  363. # for enterprise_name in company_list:
  364. # _v = _db.get(enterprise_name)
  365. # if _v is None:
  366. # if isLegalNewName(enterprise_name):
  367. # _db.set(enterprise_name,1)
  368. # 新实体合法判断
  369. def isLegalNewName(enterprise_name):
  370. # head_character_list = ["[",'【',"(",'(']
  371. # tail_character_list = ["]",'】',")",')']
  372. # 名称开头判断
  373. if re.search("^[\da-zA-Z][^\da-zA-Z]|"
  374. "^[^\da-zA-Z\u4e00-\u9fa5\[【((]|"
  375. "^[\[【((].{,1}[\]】))]|"
  376. "^[0〇]|"
  377. "^(20[0-2][0-9]|[0-2]?[0-9]年|[0-1]?[0-9]月|[0-3]?[0-9]日)",enterprise_name):
  378. return -1
  379. if len(re.findall("[\u4e00-\u9fa5]",enterprise_name))<2:
  380. return -1
  381. if re.search("╳|*|\*|×|xx|XX",enterprise_name):
  382. return -1
  383. if re.search("^(省|自治[县州区]|市|县|区|镇|乡|街道)",enterprise_name) and not re.search("^(镇江|乡宁|镇原|镇海|镇安|镇巴|镇坪|镇赉|镇康|镇沅|镇雄|镇远|镇宁|乡城|镇平|市中|市南|市北)",enterprise_name):
  384. return -1
  385. if re.search("\d{1,2}:\d{2}(:\d{2})?|(rar|xlsx|zip|png|jpg|swf|docx|txt|pdf|PDF|doc|xls|bmp|&?nbsp)",enterprise_name):
  386. return -1
  387. if re.search("(招标|代理)(人|机构)|联系(人|方式)|中标|候选|第.名",enterprise_name):
  388. return -1
  389. if re.search("[a-zA-Z\d]{1,2}(包|标段?)|第.批"):
  390. return 0
  391. return 1
  392. # 过滤掉Redis里值为0的错误实体
  393. def enterprise_filter(entity_list):
  394. global ENTERPRISE_HUGE,SET_ENTERPRISE,POOL_REDIS
  395. if ENTERPRISE_HUGE:
  396. if POOL_REDIS is None:
  397. init_redis_pool()
  398. _db = POOL_REDIS.getConnector()
  399. remove_list = []
  400. try:
  401. for entity in entity_list:
  402. if entity.entity_type in ['company','org']:
  403. _v = _db.get(entity.entity_text)
  404. if _v==0:
  405. remove_list.append(entity)
  406. except Exception as e:
  407. traceback.print_exc()
  408. POOL_REDIS.putConnector(_db)
  409. for _entity in remove_list:
  410. entity_list.remove(_entity)
  411. return entity_list
  412. def is_enterprise_exist(enterprise_name):
  413. global ENTERPRISE_HUGE,SET_ENTERPRISE,POOL_REDIS
  414. # print("test",enterprise_name)
  415. if ENTERPRISE_HUGE:
  416. if POOL_REDIS is None:
  417. init_redis_pool()
  418. _db = POOL_REDIS.getConnector()
  419. try:
  420. _time = time.time()
  421. _v = _db.get(enterprise_name)
  422. POOL_REDIS.putConnector(_db)
  423. if _v is None:
  424. return False
  425. else:
  426. if _v:
  427. # log("redis take %.5f of '%s' exists"%(time.time()-_time,enterprise_name))
  428. return True
  429. else:
  430. return False
  431. except Exception as e:
  432. traceback.print_exc()
  433. return False
  434. else:
  435. if enterprise_name in SET_ENTERPRISE:
  436. return True
  437. else:
  438. return False
  439. import threading
  440. import time
  441. load_enterprise_thread = threading.Thread(target=getDict_enterprise)
  442. load_enterprise_thread.start()
  443. MAX_ENTERPRISE_LEN = 30
  444. def match_enterprise_max_first(sentence):
  445. while True:
  446. if not DICT_ENTERPRISE_DONE:
  447. time.sleep(1)
  448. else:
  449. break
  450. list_match = []
  451. begin_index = 0
  452. if len(sentence)>4:
  453. while True:
  454. if begin_index+ENTERPRISE_KEY_LEN<len(sentence):
  455. key_enter = sentence[begin_index:begin_index+ENTERPRISE_KEY_LEN]
  456. # if key_enter in DICT_ENTERPRISE:
  457. # _len = min(MAX_ENTERPRISE_LEN-ENTERPRISE_KEY_LEN+1,len(sentence)-begin_index)
  458. # for _i in range(_len):
  459. # enter_name = sentence[begin_index+ENTERPRISE_KEY_LEN:begin_index+_len-_i]
  460. # if enter_name in DICT_ENTERPRISE[key_enter]:
  461. # match_item = {"entity_text":"%s%s"%(key_enter,enter_name),"begin_index":begin_index,"end_index":begin_index+len(key_enter)+len(enter_name)}
  462. # list_match.append(match_item)
  463. # begin_index += (len(key_enter)+len(enter_name))-1
  464. # break
  465. if key_enter in SET_PREFIX_ENTERPRISE:
  466. _len = min(MAX_ENTERPRISE_LEN-ENTERPRISE_KEY_LEN+1,len(sentence)-begin_index)
  467. for _i in range(_len):
  468. enter_name = sentence[begin_index:begin_index+_len-_i]
  469. enter_tail = enter_name[-ENTERPRISE_TAIL_LEN:]
  470. if re.search('[\u4e00-\u9fa5]', enter_tail) == None: # 20240111不包含中文后缀不要
  471. continue
  472. elif enter_name in ['黄埔军校', '五金建材', '铝合金门窗', '测试单位' ,'生产管理部', '华电XXX发电有限公司']: # '国有资产管理处',
  473. continue
  474. elif re.search('^\w{,3}(有限)?(责任)?分?公司$|^第[一二三四五六七八九十](工程|建筑)?分?公司$|交汇处$|大厦$|大楼$|^华电X{1,4}发电有限公司$', enter_name):
  475. continue
  476. if len(enter_name)<4: # 20240521 短于4个字的不要
  477. break
  478. if enter_tail in SET_TAIL_ENTERPRISE or re.search('(中心|中学|小学|医院|学院|大学|学校|监狱|大队|支队|林场|海关|分局|商行)$', enter_tail):
  479. have_bus, dic = get_business_data(enter_name) # 20210124 改为有工商数据的实体才添加
  480. if have_bus:
  481. # if is_enterprise_exist(enter_name):
  482. match_item = {"entity_text":"%s"%(enter_name),"begin_index":begin_index,"end_index":begin_index+len(enter_name)}
  483. # print("match_item",key_enter,enter_name)
  484. list_match.append(match_item)
  485. begin_index += len(enter_name)-1
  486. break
  487. begin_index += 1
  488. else:
  489. break
  490. # print("======",list_match)
  491. return list_match
  492. def calibrateEnterprise(list_articles,list_sentences,list_entitys):
  493. for _article,list_sentence,list_entity in zip(list_articles,list_sentences,list_entitys):
  494. list_calibrate = []
  495. match_add = False
  496. match_replace = False
  497. range_entity = []
  498. for p_entity in list_entity:
  499. if p_entity.entity_type in ("org","company","location"):
  500. range_entity.append(p_entity)
  501. if len(range_entity)>1000:
  502. break
  503. for p_sentence in list_sentence:
  504. sentence = p_sentence.sentence_text
  505. 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']]
  506. list_match = match_enterprise_max_first(sentence)
  507. # print("list_match", list_match)
  508. doc_id = p_sentence.doc_id
  509. sentence_index = p_sentence.sentence_index
  510. tokens = p_sentence.tokens
  511. list_match.sort(key=lambda x:x["begin_index"])
  512. for _match_index in range(len(list_match)):
  513. _match = list_match[_match_index]
  514. find_flag = False
  515. for p_entity in range_entity:
  516. if p_entity.sentence_index!=p_sentence.sentence_index:
  517. continue
  518. if p_entity.entity_type=="location" and p_entity.entity_text==_match["entity_text"]:
  519. find_flag = True
  520. p_entity.entity_type = "company"
  521. p_entity.if_dict_match = 1
  522. if p_entity.entity_type not in ["location","org","company"]:
  523. continue
  524. if _match["entity_text"] == p_entity.entity_text:
  525. p_entity.if_dict_match = 1
  526. #有重叠
  527. #match部分被包含则不处理
  528. if _match["begin_index"]>=p_entity.wordOffset_begin and _match["end_index"]<=p_entity.wordOffset_end:
  529. find_flag = True
  530. # 判断是否是多个公司
  531. if re.search('[分支](公司|中心|监狱|部|行)|^\w{4,15}公司\w{2,3}公司$'
  532. '|(大学|学院)\w{,2}附属\w{,6}医院$|(\w{2,5}办事处\w{2,6}$'
  533. '|\w{2,4}[省市县]\w{2,14}村)(股份)?经济(合作|联合)社$|国家税务总局\w{2,10}税务局$',
  534. p_entity.entity_text):
  535. continue
  536. if p_entity.entity_type == "location" and re.search('\d[楼室号]', p_entity.entity_text): # 明确地址不进行替换避免 类似 434052508 西宁市城西区西关大街128号山东大厦15楼1152室 更新为 西宁市城西
  537. continue
  538. for _match_j in range(_match_index,len(list_match)):
  539. if not list_match[_match_j]["end_index"]<=p_entity.wordOffset_end:
  540. _match_j -= 1
  541. break
  542. if _match_j>_match_index:
  543. match_replace = True
  544. match_add = True
  545. begin_index = changeIndexFromWordToWords(tokens,_match["begin_index"])
  546. end_index = changeIndexFromWordToWords(tokens,_match["end_index"]-1)
  547. list_calibrate.append({"type":"update","from":p_entity.entity_text,"to":_match["entity_text"]})
  548. p_entity.entity_text = _match["entity_text"]
  549. p_entity.wordOffset_begin = _match["begin_index"]
  550. p_entity.wordOffset_end = _match["end_index"]
  551. p_entity.begin_index = begin_index
  552. p_entity.end_index = end_index
  553. # 该公司实体是字典识别的
  554. p_entity.if_dict_match = 1
  555. for _match_h in range(_match_index+1,_match_j+1):
  556. entity_text = list_match[_match_h]["entity_text"]
  557. entity_type = "company"
  558. begin_index = changeIndexFromWordToWords(tokens,list_match[_match_h]["begin_index"])
  559. end_index = changeIndexFromWordToWords(tokens,list_match[_match_h]["end_index"]-1)
  560. entity_id = "%s_%d_%d_%d"%(doc_id,sentence_index,begin_index,end_index)
  561. 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)
  562. add_entity.if_dict_match = 1
  563. list_entity.append(add_entity)
  564. range_entity.append(add_entity)
  565. list_calibrate.append({"type":"add","from":"","to":entity_text})
  566. _match_index = _match_j
  567. break
  568. continue
  569. elif _match["begin_index"]<=p_entity.wordOffset_begin and _match["end_index"]>p_entity.wordOffset_begin:
  570. find_flag = True
  571. if _match["begin_index"]<p_entity.wordOffset_begin and _match["end_index"]<=p_entity.wordOffset_end:
  572. if p_entity.entity_type in ("org","company"):
  573. _diff_text = sentence[p_entity.wordOffset_end:_match["end_index"]]
  574. if re.search("分",_diff_text) is not None:
  575. pass
  576. else:
  577. match_replace = True
  578. begin_index = changeIndexFromWordToWords(tokens,_match["begin_index"])
  579. end_index = changeIndexFromWordToWords(tokens,_match["end_index"]-1)
  580. list_calibrate.append({"type":"update","from":p_entity.entity_text,"to":_match["entity_text"]})
  581. p_entity.entity_text = _match["entity_text"]
  582. p_entity.wordOffset_begin = _match["begin_index"]
  583. p_entity.wordOffset_end = _match["end_index"]
  584. p_entity.begin_index = begin_index
  585. p_entity.end_index = end_index
  586. p_entity.if_dict_match = 1
  587. elif _match["end_index"]>=p_entity.wordOffset_end:
  588. # 原entity列表已有实体,则不重复添加
  589. if (_match["entity_text"],_match["begin_index"],_match["end_index"]) not in sentence_entitys:
  590. match_replace = True
  591. begin_index = changeIndexFromWordToWords(tokens,_match["begin_index"])
  592. end_index = changeIndexFromWordToWords(tokens,_match["end_index"]-1)
  593. list_calibrate.append({"type":"update","from":p_entity.entity_text,"to":_match["entity_text"]})
  594. p_entity.entity_text = _match["entity_text"]
  595. p_entity.wordOffset_begin = _match["begin_index"]
  596. p_entity.wordOffset_end = _match["end_index"]
  597. p_entity.begin_index = begin_index
  598. p_entity.end_index = end_index
  599. p_entity.entity_type = "company"
  600. p_entity.if_dict_match = 1
  601. elif _match["begin_index"]<p_entity.wordOffset_end and _match["end_index"]>p_entity.wordOffset_end:
  602. find_flag = True
  603. if p_entity.entity_type in ("org","company"):
  604. match_replace = True
  605. begin_index = changeIndexFromWordToWords(tokens,_match["begin_index"])
  606. end_index = changeIndexFromWordToWords(tokens,_match["end_index"]-1)
  607. list_calibrate.append({"type":"update","from":p_entity.entity_text,"to":_match["entity_text"]})
  608. p_entity.entity_text = _match["entity_text"]
  609. p_entity.wordOffset_begin = _match["begin_index"]
  610. p_entity.wordOffset_end = _match["end_index"]
  611. p_entity.begin_index = begin_index
  612. p_entity.end_index = end_index
  613. p_entity.if_dict_match = 1
  614. if not find_flag:
  615. match_add = True
  616. entity_text = _match["entity_text"]
  617. entity_type = "company"
  618. begin_index = changeIndexFromWordToWords(tokens,_match["begin_index"])
  619. end_index = changeIndexFromWordToWords(tokens,_match["end_index"]-1)
  620. entity_id = "%s_%d_%d_%d"%(doc_id,sentence_index,begin_index,end_index)
  621. 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)
  622. list_entity.append(add_entity)
  623. range_entity.append(add_entity)
  624. list_calibrate.append({"type":"add","from":"","to":entity_text})
  625. #去重
  626. set_calibrate = set()
  627. list_match_enterprise = []
  628. for _calibrate in list_calibrate:
  629. _from = _calibrate.get("from","")
  630. _to = _calibrate.get("to","")
  631. _key = _from+_to
  632. if _key not in set_calibrate:
  633. list_match_enterprise.append(_calibrate)
  634. set_calibrate.add(_key)
  635. match_enterprise_type = 0
  636. if match_add:
  637. match_enterprise_type += 1
  638. if match_replace:
  639. match_enterprise_type += 2
  640. _article.match_enterprise = list_match_enterprise
  641. _article.match_enterprise_type = match_enterprise_type
  642. def isLegalEnterprise(name):
  643. is_legal = True
  644. if re.search("^[省市区县]",name) is not None or re.search("^\**.{,3}(分(公司|行|支)|街道|中心|办事处|经营部|委员会|有限公司)$",name) or re.search("标段|标包|名称|联系人|联系方式|中标单位|中标人|测试单位|采购单位|采购人|代理人|代理机构|盖章|(主)",name) is not None:
  645. is_legal = False
  646. return is_legal
  647. def fix_LEGAL_ENTERPRISE():
  648. unlegal_enterprise = []
  649. _path = getEnterprisePath()
  650. _sum = 0
  651. set_enter = set()
  652. paths = [_path]
  653. for _p in paths:
  654. with open(_p,"r",encoding="utf8") as f:
  655. while True:
  656. line = f.readline()
  657. if not line:
  658. break
  659. line = line.strip()
  660. if isLegalEnterprise(line):
  661. set_enter.add(line)
  662. if line=="有限责任公司" or line=='设计研究院' or line=='限责任公司' or (re.search("^.{,4}(分公司|支行|分行)$",line) is not None and re.search("电信|移动|联通|建行|工行|农行|中行|交行",line) is None):
  663. print(line)
  664. if line in set_enter:
  665. set_enter.remove(line)
  666. with open("enter.txt","w",encoding="utf8") as fwrite:
  667. for line in list(set_enter):
  668. fwrite.write(line.replace("(","(").replace(")",")"))
  669. fwrite.write("\n")
  670. # if re.search("标段|地址|标包|名称",line) is not None:#\(|\)||
  671. # _count += 1
  672. # print("=",line)
  673. # print("%d/%d"%(_count,_sum))
  674. # a_list = []
  675. # with open("电信分公司.txt","r",encoding="utf8") as f:
  676. # while True:
  677. # _line = f.readline()
  678. # if not _line:
  679. # break
  680. # if _line.strip()!="":
  681. # a_list.append(_line.strip())
  682. # with open("enter.txt","a",encoding="utf8") as f:
  683. # for _line in a_list:
  684. # f.write(_line)
  685. # f.write("\n")
  686. if __name__=="__main__":
  687. # edit_distance("GUMBO","GAMBOL")
  688. # print(jaccard_score("周口经济开发区陈营运粮河两岸拆迁工地土工布覆盖项目竞争性谈判公告","周口经济开发区陈营运粮河两岸拆迁工地土工布覆盖项目-成交公告"))
  689. #
  690. # sentences = "广州比地数据科技有限公司比地数据科技有限公司1111111123沈阳南光工贸有限公司"
  691. # print(match_enterprise_max_first(sentences))
  692. #
  693. # print("takes %d s"%(time.time()-_time))
  694. # fix_LEGAL_ENTERPRISE()
  695. # print(jaccard_score("吉林省九台","吉林省建苑设计集团有限公司"))
  696. print(match_enterprise_max_first("中国南方航空股份有限公司黑龙江分公司"))