label.py 75 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770
  1. '''
  2. Created on 2019年6月4日
  3. @author: User
  4. '''
  5. # DEPRECATED(Phase1): 本文件中的 PostgreSQL 硬编码连接(host=192.168.*,
  6. # password=postgres 等)将在后续 training/ Phase 迁移到 BiddingKG.dl.infra.db。
  7. # 迁移完成前可临时使用:from BiddingKG.dl.infra.db import get_connection;
  8. # conn = get_connection("<dbname>")
  9. # 详见 ARCHITECTURE.md 第 11 章 Phase 1 与 REFACTOR_LOG.md。
  10. import fool
  11. #import BiddingKG.dl.interface.Preprocessing as Preprocessing
  12. from bs4 import BeautifulSoup
  13. import re
  14. import codecs
  15. from BiddingKG.dl.common.Utils import save,load, findAllIndex
  16. import glob
  17. import threading
  18. import numpy as np
  19. import time
  20. from zipfile import ZipFile
  21. import json
  22. import psycopg2
  23. import pandas as pd
  24. import math
  25. from BiddingKG.dl.foolnltk.bi_lstm_crf import BiLSTM
  26. import copy
  27. from BiddingKG.dl.interface.Entitys import *
  28. from BiddingKG.dl.foolnltk.Entity2DB import *
  29. import tensorflow as tf
  30. import requests
  31. def getNers(sentences,MAXAREA = 100000,userselffool=False):
  32. '''
  33. @param: sentences:句子数
  34. @return 限流执行后的分词和实体识别list
  35. '''
  36. def getData(ners,process_data):
  37. process_sentences = [item[1] for item in process_data]
  38. if userselffool:
  39. ner_ = Preprocessing.selffool.ner(process_sentences)
  40. else:
  41. ner_ = fool.ner(process_sentences)
  42. for i in range(len(ner_)):
  43. the_index = process_data[i][0]
  44. ners[the_index] = ner_[i]
  45. sents = []
  46. for i in range(len(sentences)):
  47. sents.append([i,sentences[i]])
  48. sents.sort(key=lambda x:len(x[1]),reverse=True)
  49. index_ = 0
  50. ners = [[]for i in range(len(sentences))]
  51. while(True):
  52. width = len(sents[index_][1])
  53. height = MAXAREA//width+1
  54. if height>len(sents)-index_:
  55. height = len(sents)-index_
  56. process_data = sents[index_:index_+height]
  57. getData(ners, process_data)
  58. index_ += height
  59. if index_>=len(sents):
  60. break
  61. return ners
  62. def preprocess(list_articles):
  63. '''
  64. @summary: 预处理文本,将foolnltk的识别结果存储到数据库,方便查看和修正
  65. '''
  66. import psycopg2
  67. conn = psycopg2.connect(dbname="article_label",user="postgres",password="postgres",host="192.168.2.101")
  68. list_filename_text = []
  69. cursor = conn.cursor()
  70. for article in list_articles:
  71. doc_id = article[0]
  72. text = Preprocessing.segment(Preprocessing.tableToText(BeautifulSoup(article[1],"lxml")))
  73. list_filename_text.append([doc_id,text,article[2]])
  74. list_sent = []
  75. for x in re.split("[。]", text):
  76. if len(x)>0:
  77. list_sent.append(x+"。")
  78. for n in getNers(list_sent):
  79. for _entity in n:
  80. print(_entity)
  81. sql = " insert into fool_ner_train(filename,begin_index,end_index,type,text) values('"+str(doc_id)+"',"+str(_entity[0])+","+str(_entity[1])+",'"+str(_entity[2])+"','"+str(_entity[3])+"')"
  82. cursor.execute(sql)
  83. conn.commit()
  84. conn.close()
  85. return list_filename_text
  86. def hasNotBeenLabeled(items,code_begin,code):
  87. for i in range(code_begin,code_begin+len(code)):
  88. if items[i][1]!="O":
  89. return False
  90. return True
  91. def findAllIndex(substr,wholestr):
  92. copystr = wholestr
  93. result = []
  94. indexappend = 0
  95. while(True):
  96. index = copystr.find(substr)
  97. if index<0:
  98. break
  99. else:
  100. result.append(indexappend+index)
  101. indexappend += index+len(substr)
  102. copystr = copystr[index+len(substr):]
  103. return result
  104. def labelEntity():
  105. '''
  106. @summary: 标注数据,从数据库中查询实体信息,生成对文本生成标签数据
  107. '''
  108. import psycopg2
  109. conn = psycopg2.connect(dbname="article_label",user="postgres",password="postgres",host="192.168.2.101")
  110. cursor = conn.cursor()
  111. list_filename_text = load("list_filename_text_wrongEntity.pk")
  112. list_sent_label = []
  113. list_text_label = []
  114. sql = " select distinct filename from fool_ner t where not exists(select 1 from fool_ner a where t.filename=a.filename and type_0 in('org','company') and new_type is NULL) "
  115. cursor.execute(sql)
  116. set_filename = set()
  117. for row in cursor.fetchall():
  118. set_filename.add(row[0])
  119. for filename_text in list_filename_text:
  120. filename = filename_text[0]
  121. text = filename_text[1]
  122. if filename not in set_filename:
  123. continue
  124. sql = " select text,type_0,new_text,new_type from fool_ner where filename='"+filename+"' group by text,type_0,new_text,new_type"
  125. print(sql)
  126. cursor.execute(sql)
  127. rows = cursor.fetchall()
  128. rows.sort(key=lambda x:len(x[0]))
  129. list_entity = []
  130. for row in rows:
  131. entity = row[0]
  132. type = row[1]
  133. new_entity = row[2]
  134. new_type = row[3]
  135. _entitys = []
  136. if new_type is None or new_type=="" or new_type=="nan":
  137. _type = type
  138. else:
  139. _type = new_type
  140. if new_entity=="1":
  141. continue
  142. elif new_entity is None or new_entity =="" or new_entity=="nan":
  143. list_entity.append([entity,_type])
  144. _entitys.append([entity,_type])
  145. else:
  146. for _entity in new_entity.split("##"):
  147. list_entity.append([_entity,_type])
  148. _entitys.append([_entity,_type])
  149. if len(_entitys)>=2:
  150. data_item = []
  151. for i in range(len(str(entity))):
  152. _item = []
  153. _item.append(entity[i])
  154. _item.append("O")
  155. data_item.append(_item)
  156. for _entity_type in _entitys:
  157. _entity = _entity_type[0]
  158. _type = _entity_type[1]
  159. if _type not in ["person","company","org","job","time","location"]:
  160. continue
  161. for _index in findAllIndex(_entity, entity):
  162. _find_flag = True
  163. if len(_entity)==1:
  164. if hasNotBeenLabeled(data_item, _index, _entity):
  165. data_item[_index][1] = "S_"+_type
  166. else:
  167. if hasNotBeenLabeled(data_item, _index, _entity):
  168. for j in range(_index,_index+len(_entity)):
  169. if j==_index:
  170. data_item[j][1] = "B_"+_type
  171. elif j==_index+len(_entity)-1:
  172. data_item[j][1] = "E_"+_type
  173. else:
  174. data_item[j][1] = "M_"+_type
  175. if _find_flag:
  176. list_text_label.append(data_item)
  177. list_insert = [" ","根据","就","受",",",",","。",":",":","#","&","$","、","/","-","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","RR","S","TA","U","V","Wa","X","YG","Z","a","b","c","d","e","f","g"]
  178. for insert_item in list_insert:
  179. if np.random.random()>0.7:
  180. copy_data_item = copy.copy(data_item)
  181. list_index = []
  182. for i in range(len(copy_data_item)):
  183. _split = copy_data_item[i][1].split("_")
  184. if len(_split)==2:
  185. if _split[0]=="B":
  186. list_index.append(i)
  187. if _split[0]=="E":
  188. list_index.append(i+1)
  189. list_index.sort(key=lambda x:x,reverse=True)
  190. for _index in list_index:
  191. if np.random.random()>0.5:
  192. for j in range(len(insert_item)):
  193. copy_data_item.insert(_index+j,[insert_item[j],"O"])
  194. if np.random.random()>0.5:
  195. break
  196. list_text_label.append(copy_data_item)
  197. ''''''
  198. list_entity.sort(key=lambda x:len(x[0]),reverse=True)
  199. for _sent in text.split("。"):
  200. _sent+= "。"
  201. _find_flag = False
  202. data_item = []
  203. for i in range(len(str(_sent))):
  204. _item = []
  205. _item.append(_sent[i])
  206. _item.append("O")
  207. data_item.append(_item)
  208. for _entity_type in list_entity:
  209. _entity = _entity_type[0]
  210. _type = _entity_type[1]
  211. if _type not in ["person","company","org","job","time","location"]:
  212. continue
  213. for _index in findAllIndex(_entity, _sent):
  214. _find_flag = True
  215. if len(_entity)==1:
  216. if hasNotBeenLabeled(data_item, _index, _entity):
  217. data_item[_index][1] = "S_"+_type
  218. else:
  219. if hasNotBeenLabeled(data_item, _index, _entity):
  220. for j in range(_index,_index+len(_entity)):
  221. if j==_index:
  222. data_item[j][1] = "B_"+_type
  223. elif j==_index+len(_entity)-1:
  224. data_item[j][1] = "E_"+_type
  225. else:
  226. data_item[j][1] = "M_"+_type
  227. #根据句子中是否包含实体来判断是否加入训练数据
  228. if _find_flag:
  229. list_sent_label.append(data_item)
  230. else:
  231. if np.random.random()>0.9:
  232. list_sent_label.append(data_item)
  233. ''''''
  234. with codecs.open("ner_label.txt","w",encoding="utf8") as f:
  235. for _sent_label in list_sent_label:
  236. for _word,_label in _sent_label:
  237. f.write(_word+" "+_label+"\n")
  238. f.write("\n")
  239. f.flush()
  240. with codecs.open("ner_label_split.txt","w",encoding="utf8") as f:
  241. for _sent_label in list_text_label:
  242. for _word,_label in _sent_label:
  243. f.write(_word+" "+_label+"\n")
  244. f.write("\n")
  245. f.flush()
  246. return list_sent_label
  247. class MyThread(threading.Thread):
  248. def __init__(self,func,args=()):
  249. super(MyThread,self).__init__()
  250. self.func = func
  251. self.args = args
  252. def run(self):
  253. self.result = self.func(*self.args)
  254. def get_result(self):
  255. try:
  256. return self.result # 如果子线程不使用join方法,此处可能会报没有self.result的错误
  257. except Exception:
  258. return None
  259. def deal():
  260. list_articles = []
  261. path = "C:\\Users\\User\\Desktop\\fool语料\\*.html"
  262. set_doc_id = set()
  263. for file in glob.glob(path):
  264. filename = file.split("\\")[-1]
  265. doc_id = filename.split("_")[-1][:-5]
  266. text = codecs.open(file,"r",encoding="utf8").read()
  267. wrong_entity = "".join(filename.split("_")[:-1])
  268. if doc_id in set_doc_id:
  269. for item in list_articles:
  270. if doc_id==item[0]:
  271. item[2].append(wrong_entity)
  272. else:
  273. set_doc_id.add(doc_id)
  274. list_articles.append([doc_id,text,[wrong_entity]])
  275. save(list_articles,"list_filename_html_wrongEntity.pk")
  276. def dataSplit(data,parts=2):
  277. _index = 0
  278. part_len = len(data)//parts
  279. while(True):
  280. if _index+part_len<len(data):
  281. yield data[_index:_index+part_len]
  282. _index += part_len
  283. else:
  284. yield data[_index:]
  285. break
  286. def makeFoolTrainData():
  287. '''
  288. @summary: 生成fool训练数据
  289. '''
  290. import psycopg2
  291. conn = psycopg2.connect(dbname="article_label",user="postgres",password="postgres",host="192.168.2.101")
  292. list_articles = []
  293. #list_path = ["C:\\Users\\User\\Desktop\\20190306要素\\*.html","C:\\Users\\User\\Desktop\\20190320要素\\*.html"]
  294. list_path = ["C:\\Users\\User\\Desktop\\data_20190703\\*.html"]
  295. set_doc_id = set()
  296. for path in list_path:
  297. for file in glob.glob(path):
  298. filename = file.split("\\")[-1]
  299. text = codecs.open(file,"r",encoding="utf8").read()
  300. if filename in set_doc_id:
  301. continue
  302. else:
  303. set_doc_id.add(filename)
  304. list_articles.append([filename,text])
  305. list_filename_text = []
  306. cursor = conn.cursor()
  307. _count = 0
  308. for article in list_articles:
  309. _count += 1
  310. print(str(_count)+"/"+str(len(list_articles)))
  311. doc_id = article[0]
  312. text = Preprocessing.segment(Preprocessing.tableToText(BeautifulSoup(article[1],"lxml")))
  313. list_filename_text.append([doc_id,text])
  314. list_sent = []
  315. for x in re.split("[。]", text):
  316. if len(x)>0:
  317. list_sent.append(x+"。")
  318. for n in getNers(list_sent,userselffool=True):
  319. for _entity in n:
  320. sql = " insert into fool_ner_train_1(filename,begin_index,end_index,type_0,text) values('"+str(doc_id)+"',"+str(_entity[0])+","+str(_entity[1])+",'"+str(_entity[2])+"','"+str(_entity[3])+"')"
  321. cursor.execute(sql)
  322. conn.commit()
  323. conn.close()
  324. save(list_filename_text,"list_filename_text_train_1.pk")
  325. return list_filename_text
  326. def makeLabel(sent,list_entity_type):
  327. _find_flag = False
  328. data_item = []
  329. list_entity_type.sort(key=lambda x:len(x[0]),reverse=True)
  330. for i in range(len(str(sent))):
  331. _item = []
  332. _item.append(sent[i])
  333. _item.append("O")
  334. data_item.append(_item)
  335. for _entity_type in list_entity_type:
  336. _entity = _entity_type[0]
  337. _type = _entity_type[1]
  338. if _type not in ["person","company","org","job","time","location"]:
  339. continue
  340. for _index in findAllIndex(_entity, sent):
  341. _find_flag = True
  342. if len(_entity)==1:
  343. if hasNotBeenLabeled(data_item, _index, _entity):
  344. data_item[_index][1] = "S_"+_type
  345. else:
  346. if hasNotBeenLabeled(data_item, _index, _entity):
  347. for j in range(_index,_index+len(_entity)):
  348. if j==_index:
  349. data_item[j][1] = "B_"+_type
  350. elif j==_index+len(_entity)-1:
  351. data_item[j][1] = "E_"+_type
  352. else:
  353. data_item[j][1] = "M_"+_type
  354. return data_item,_find_flag
  355. def makeTrainTxt():
  356. '''
  357. @summary: 生成训练数据文本
  358. '''
  359. import psycopg2
  360. conn = psycopg2.connect(dbname="article_label",user="postgres",password="postgres",host="192.168.2.101")
  361. cursor = conn.cursor()
  362. list_filename_text = load("list_filename_text_train.pk")
  363. list_sent_label = []
  364. list_text_label = []
  365. for filename_text in list_filename_text:
  366. filename = filename_text[0]
  367. text = filename_text[1]
  368. sql = " select text,type_0,new_text,new_type from fool_ner_train where filename='"+filename+"' group by text,type_0,new_text,new_type"
  369. print(sql)
  370. cursor.execute(sql)
  371. rows = cursor.fetchall()
  372. rows.sort(key=lambda x:len(x[0]))
  373. list_entity = []
  374. for row in rows:
  375. entity = row[0]
  376. type = row[1]
  377. new_entity = row[2]
  378. new_type = row[3]
  379. _entitys = []
  380. if new_type is None or new_type=="" or new_type=="nan":
  381. _type = type
  382. else:
  383. _type = new_type
  384. if new_entity=="1":
  385. continue
  386. elif new_entity is None or new_entity =="" or new_entity=="nan":
  387. list_entity.append([entity,_type])
  388. _entitys.append([entity,_type])
  389. else:
  390. for _entity in new_entity.split("##"):
  391. list_entity.append([_entity,_type])
  392. _entitys.append([_entity,_type])
  393. if len(_entitys)>=2:
  394. data_item = []
  395. for i in range(len(str(entity))):
  396. _item = []
  397. _item.append(entity[i])
  398. _item.append("O")
  399. data_item.append(_item)
  400. for _entity_type in _entitys:
  401. _entity = _entity_type[0]
  402. _type = _entity_type[1]
  403. if _type not in ["person","company","org","job","time","location"]:
  404. continue
  405. for _index in findAllIndex(_entity, entity):
  406. _find_flag = True
  407. if len(_entity)==1:
  408. if hasNotBeenLabeled(data_item, _index, _entity):
  409. data_item[_index][1] = "S_"+_type
  410. else:
  411. if hasNotBeenLabeled(data_item, _index, _entity):
  412. for j in range(_index,_index+len(_entity)):
  413. if j==_index:
  414. data_item[j][1] = "B_"+_type
  415. elif j==_index+len(_entity)-1:
  416. data_item[j][1] = "E_"+_type
  417. else:
  418. data_item[j][1] = "M_"+_type
  419. if _find_flag:
  420. list_text_label.append(data_item)
  421. list_insert = ["根据","就",",",",","。",":",":"]
  422. for insert_item in list_insert:
  423. if np.random.random()>0.5:
  424. copy_data_item = copy.copy(data_item)
  425. list_index = []
  426. for i in range(len(copy_data_item)):
  427. _split = copy_data_item[i][1].split("_")
  428. if len(_split)==2:
  429. if _split[0]=="B":
  430. list_index.append(i)
  431. if _split[0]=="E":
  432. list_index.append(i+1)
  433. list_index.sort(key=lambda x:x,reverse=True)
  434. for _index in list_index:
  435. if np.random.random()>0.5:
  436. for j in range(len(insert_item)):
  437. copy_data_item.insert(_index+j,[insert_item[j],"O"])
  438. list_text_label.append(copy_data_item)
  439. list_insert = [" ","根据","就","受",",",",","。",":",":","#","&","$","、","/","-","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","RR","S","TA","U","V","Wa","X","YG","Z","a","b","c","d","e","f","g"]
  440. for insert_item in list_insert:
  441. if np.random.random()>0.7:
  442. copy_data_item = copy.copy(data_item)
  443. list_index = []
  444. for i in range(len(copy_data_item)):
  445. _split = copy_data_item[i][1].split("_")
  446. if len(_split)==2:
  447. if _split[0]=="B":
  448. list_index.append(i)
  449. if _split[0]=="E":
  450. list_index.append(i+1)
  451. list_index.sort(key=lambda x:x,reverse=True)
  452. for _index in list_index:
  453. if np.random.random()>0.5:
  454. for j in range(len(insert_item)):
  455. copy_data_item.insert(_index+j,[insert_item[j],"O"])
  456. if np.random.random()>0.5:
  457. break
  458. list_text_label.append(copy_data_item)
  459. ''''''
  460. list_entity.sort(key=lambda x:len(x[0]),reverse=True)
  461. for _sent in text.split("。"):
  462. _sent+= "。"
  463. _find_flag = False
  464. data_item = []
  465. for i in range(len(str(_sent))):
  466. _item = []
  467. _item.append(_sent[i])
  468. _item.append("O")
  469. data_item.append(_item)
  470. for _entity_type in list_entity:
  471. _entity = _entity_type[0]
  472. _type = _entity_type[1]
  473. if _type not in ["person","company","org","job","time","location"]:
  474. continue
  475. for _index in findAllIndex(_entity, _sent):
  476. _find_flag = True
  477. if len(_entity)==1:
  478. if hasNotBeenLabeled(data_item, _index, _entity):
  479. data_item[_index][1] = "S_"+_type
  480. else:
  481. if hasNotBeenLabeled(data_item, _index, _entity):
  482. for j in range(_index,_index+len(_entity)):
  483. if j==_index:
  484. data_item[j][1] = "B_"+_type
  485. elif j==_index+len(_entity)-1:
  486. data_item[j][1] = "E_"+_type
  487. else:
  488. data_item[j][1] = "M_"+_type
  489. #根据句子中是否包含实体来判断是否加入训练数据
  490. if _find_flag:
  491. list_sent_label.append(data_item)
  492. else:
  493. if np.random.random()>0.9:
  494. list_sent_label.append(data_item)
  495. ''' '''
  496. with codecs.open("ner_train.txt","w",encoding="utf8") as f:
  497. for _sent_label in list_sent_label:
  498. for _word,_label in _sent_label:
  499. f.write(_word+" "+_label+"\n")
  500. f.write("\n")
  501. f.flush()
  502. with codecs.open("ner_train_split.txt","w",encoding="utf8") as f:
  503. for _sent_label in list_text_label:
  504. for _word,_label in _sent_label:
  505. f.write(_word+" "+_label+"\n")
  506. f.write("\n")
  507. f.flush()
  508. def _load_map_file(path, char_map_name, id_map_name):
  509. with ZipFile(path) as myzip:
  510. with myzip.open('all_map.json') as myfile:
  511. content = myfile.readline()
  512. content = content.decode()
  513. data = json.loads(content)
  514. return data.get(char_map_name), data.get(id_map_name)
  515. def getContext(file):
  516. char_to_id, id_to_seg = _load_map_file("data/map.zip", "char_map", "ner_map")
  517. id_to_tag = {int(k):v for k,v in id_to_seg.items()}
  518. tag_to_id = {v:int(k) for k,v in id_to_seg.items()}
  519. list_sent_label = []
  520. with codecs.open(file,"r",encoding="utf8") as f:
  521. sentence = []
  522. while(True):
  523. line = f.readline()
  524. if not line:
  525. break
  526. if len(line)==1:
  527. if len(sentence)>0:
  528. list_sent_label.append(sentence)
  529. sentence = []
  530. else:
  531. _word_id = char_to_id.get(line[0]) if line[0] in char_to_id.keys() else char_to_id.get("<OOV>")
  532. _tag_id = tag_to_id.get(line.split()[-1].strip())
  533. sentence.append([_word_id,_tag_id])
  534. return list_sent_label
  535. def readlabeldata(file,list_context,MAX_LEN=300,keep_prob=1):
  536. '''
  537. @summary: 读取文件中的标注数据
  538. '''
  539. def addContext(_sentence,entity_sent,entity_label,id_B_company,id_E_company):
  540. _sent = []
  541. _label = []
  542. _flag = 0
  543. _find_flag = False
  544. for item in _sentence:
  545. if _flag==0:
  546. if item[1]==id_B_company:
  547. for word_id,tag_id in zip(entity_sent,entity_label):
  548. _sent.append(word_id)
  549. _label.append(tag_id)
  550. _flag = 1
  551. _find_flag = True
  552. else:
  553. _sent.append(item[0])
  554. _label.append(item[1])
  555. elif _flag==1:
  556. if item[1]==id_E_company:
  557. _flag = 2
  558. else:
  559. continue
  560. else:
  561. _sent.append(item[0])
  562. _label.append(item[1])
  563. return _sent,_label,_find_flag
  564. def spreadContext(_sent,_label,id_to_char,id_to_tag):
  565. list_sent_label = []
  566. for _word,_l in zip(_sent,_label):
  567. list_sent_label.append([id_to_char.get(_word),id_to_tag.get(_l)])
  568. print(list_sent_label)
  569. list_sent_label_lengths = []
  570. char_to_id, id_to_seg = _load_map_file("data/map.zip", "char_map", "ner_map")
  571. id_to_char = {int(v):k for k,v in char_to_id.items()}
  572. id_to_tag = {int(k):v for k,v in id_to_seg.items()}
  573. tag_to_id = {v:int(k) for k,v in id_to_seg.items()}
  574. id_B_company = tag_to_id.get("B_company")
  575. id_E_company = tag_to_id.get("E_company")
  576. with codecs.open(file,"r",encoding="utf8") as f:
  577. _sent = []
  578. _label = []
  579. while(True):
  580. line = f.readline()
  581. if not line:
  582. break
  583. if len(line)==1:
  584. if np.random.rand()<keep_prob:
  585. if len(_label)>0 and _label[0]==id_B_company and _label[-1]==id_E_company:
  586. if np.random.rand()<0.8:
  587. _int_random = np.random.randint(0,len(list_context))
  588. _sentence = list_context[_int_random]
  589. _sent_context,_label_context,_find_flag = addContext(_sentence, _sent, _label, id_B_company, id_E_company)
  590. if _find_flag:
  591. if len(_sent_context)<MAX_LEN:
  592. list_sent_label_lengths.append([_sent_context,_label_context,len(_sent_context)])
  593. else:
  594. if len(_sent)<MAX_LEN and len(_sent)>0:
  595. list_sent_label_lengths.append([_sent,_label,len(_sent)])
  596. '''
  597. print("====")
  598. spreadContext(_sent, _label, id_to_char, id_to_tag)
  599. spreadContext(_sent_context, _label_context, id_to_char, id_to_tag)
  600. print("====")
  601. '''
  602. else:
  603. if len(_sent)<MAX_LEN and len(_sent)>0:
  604. list_sent_label_lengths.append([_sent,_label,len(_sent)])
  605. _sent = []
  606. _label = []
  607. else:
  608. _sent.append(char_to_id.get(line[0]) if line[0] in char_to_id.keys() else char_to_id.get("<OOV>"))
  609. tag = line.split()[-1].strip()
  610. _label.append(tag_to_id.get(tag))
  611. return list_sent_label_lengths
  612. def gt3():
  613. '''
  614. @summary: 获取错误标签长度大于3的
  615. '''
  616. list_articles = []
  617. list_filename_html_wrongEntity = load("list_filename_html_wrongEntity.pk")
  618. for row in list_filename_html_wrongEntity:
  619. if len(row[2])>1 or len(row[2][0])>3:
  620. list_articles.append(row)
  621. print(len(list_articles))
  622. save(list_articles,"list_filename_html_wrongEntity_gt3.pk")
  623. def selectByRule():
  624. '''
  625. @summary: 从数据库中查询出符合规则的记录,方便修正
  626. '''
  627. conn = psycopg2.connect(dbname="article_label", user="postgres", password="postgres",host="192.168.2.101")
  628. cursor = conn.cursor()
  629. tables = ["fool_ner","fool_ner_train"]
  630. #tables = ["fool_ner"]
  631. for table in tables:
  632. sql = " select filename,type_0,text,new_type,new_text from "+table+" where ctid in (select max(ctid) from "+table+" where type_0 in ('org','company','location') group by filename,text) order by text "
  633. cursor.execute(sql)
  634. rows = cursor.fetchall()
  635. list_filename = []
  636. list_type_0 = []
  637. list_text = []
  638. list_new_type = []
  639. list_new_text = []
  640. pattern = "室"
  641. list_keyword = ["厂","所","出","院","部","行","局","社","采招办","酒店","办事处","分理处","管理处","集团","组织","支队","部队","支行","银行","支局","分行","分公司","公司","中心","医院","卫生院","小学","中学","大学","学校","政府","委员会","委会","财政局"]
  642. list_second_keyword = ["处","厅","园","委","队","室","站","会","办","馆","共和国","科技"]
  643. for row in rows:
  644. filename = row[0]
  645. type_0 = row[1]
  646. entity = row[2]
  647. new_type = row[3]
  648. new_entity = row[4]
  649. list_entity = []
  650. if new_type is None or new_type=="" or new_type=="nan":
  651. _type = type
  652. else:
  653. _type = new_type
  654. if new_entity=="1":
  655. continue
  656. elif new_entity is None or new_entity =="" or new_entity=="nan":
  657. list_entity.append([entity,_type,new_entity])
  658. else:
  659. for _entity in new_entity.split("##"):
  660. list_entity.append([_entity,_type,entity])
  661. _flag = False
  662. _index = 0
  663. for _entity in list_entity:
  664. '''
  665. if re.search('监狱.{,4}$',entity) is not None:
  666. _flag = True
  667. '''
  668. if (len(entity)>2 and entity[-1]==entity[-2]) or (len(entity)>4 and entity[-4:-2]==entity[-2:]):
  669. _flag = True
  670. '''
  671. pattern = "|".join(list_keyword)
  672. for _iter in re.finditer(pattern,text):
  673. if _iter.span()[1]>_index:
  674. _index = _iter.span()[1]
  675. new_text = text[:_index]
  676. if _index == 0:
  677. for _iter in re.finditer("|".join(list_second_keyword),text):
  678. if _iter.span()[1]>_index:
  679. _index = _iter.span()[1]
  680. new_text = text[:_index]
  681. '''
  682. '''
  683. for keyword in list_keyword:
  684. if _flag:
  685. break
  686. allindex = findAllIndex(keyword, text)
  687. if len(allindex)>0:
  688. _flag = True
  689. _index = allindex[-1]+len(keyword)
  690. new_text = text[:_index]
  691. '''
  692. if _flag:
  693. list_filename.append(filename)
  694. list_type_0.append(type_0)
  695. list_text.append(entity)
  696. list_new_type.append(new_type)
  697. list_new_text.append(new_entity)
  698. data = {"list_filename":list_filename,"list_type_0":list_type_0,"list_text":list_text,"list_new_type":list_new_type,"list_new_text":list_new_text}
  699. df = pd.DataFrame(data,columns=["list_filename","list_type_0","list_text","list_new_type","list_new_text"])
  700. df.to_excel(table+".xls")
  701. def makeDict_filename_content():
  702. dict_filename_content = {}
  703. path = "C:\\Users\\User\\Desktop\\fool语料\\*.html"
  704. set_doc_id = set()
  705. for file in glob.glob(path):
  706. filename = file.split("\\")[-1]
  707. doc_id = filename.split("_")[-1][:-5]
  708. text = codecs.open(file,"r",encoding="utf8").read()
  709. dict_filename_content[doc_id] = text
  710. list_path = ["C:\\Users\\User\\Desktop\\20190416要素\\*.html","C:\\Users\\User\\Desktop\\20190306要素\\*.html","C:\\Users\\User\\Desktop\\20190320要素\\*.html","C:\\Users\\User\\Desktop\\data_20190703\\*.html","C:\\Users\\User\\Desktop\\20190715\\*.html"]
  711. for path in list_path:
  712. for file in glob.glob(path):
  713. filename = file.split("\\")[-1]
  714. text = codecs.open(file,"r",encoding="utf8").read()
  715. dict_filename_content[filename] = text
  716. save(dict_filename_content,"dict_filename_content.pk")
  717. def importLabelData():
  718. conn = psycopg2.connect(dbname="article_label", user="postgres", password="postgres",host="192.168.2.101")
  719. cursor = conn.cursor()
  720. for file in glob.glob("label/*.xls"):
  721. if len(file.split("_"))>1:
  722. table = "fool_ner"
  723. else:
  724. table = "fool_ner_train"
  725. print(file,table)
  726. df = pd.read_excel(file)
  727. for filename,type_0,text,new_type,new_text in zip(df["list_filename"],df["list_type_0"],df["list_text"],df["list_new_type"],df["list_new_text"]):
  728. sql = " insert into "+table+" (filename,type_0,text,new_type,new_text) values('"+str(filename).replace(".0","")+"','"+str(type_0)+"','"+str(text)+"','"+str(new_type)+"','"+str(new_text)+"')"
  729. #sql = " update "+table+" set new_text='"+str(new_text)+"',new_type='"+str(new_type)+"' where filename='"+str(filename)+"' and text='"+str(text)+"' "
  730. cursor.execute(sql)
  731. conn.commit()
  732. conn.close()
  733. def checklabel():
  734. '''
  735. @summary: 检查label是否标注正确
  736. '''
  737. with codecs.open("ner_train.txt","r",encoding="utf8") as f:
  738. a = ""
  739. b = ""
  740. c = ""
  741. _index = 0
  742. while(True):
  743. _index += 1
  744. line = f.readline()
  745. if not line:
  746. break
  747. c = line.split(" ")[0].strip()
  748. if a=="新" and b=="乡" and c=="华":
  749. print(_index)
  750. a = b
  751. b = c
  752. def updateLabel():
  753. '''
  754. @summary: 更新标注数据
  755. '''
  756. conn = psycopg2.connect(dbname="article_label", user="postgres", password="postgres",host="192.168.2.101")
  757. cursor = conn.cursor()
  758. tables = ["fool_ner","fool_ner_train"]
  759. for table in tables:
  760. file = table+".xls"
  761. df = pd.read_excel(file)
  762. for filename,type_0,text,new_type,new_text in zip(df["list_filename"],df["list_type_0"],df["list_text"],df["list_new_type"],df["list_new_text"]):
  763. sql = " update "+table+" set new_type='"+str(new_type)+"',new_text='"+str(new_text)+"' where filename='"+str(filename).replace(".0","")+"' and text='"+str(text)+"'"
  764. print(sql)
  765. cursor.execute(sql)
  766. conn.commit()
  767. conn.close()
  768. def makeCertainEntity():
  769. fileList = ["C:\\Users\\User\\Desktop\\cleanedEntity.tsv","C:\\Users\\User\\Desktop\\company_found.tsv"]
  770. for file in fileList:
  771. outfile = file.split(".")[0]+".txt"
  772. with codecs.open(outfile,"w",encoding="utf8") as f_w:
  773. with codecs.open(file,"r",encoding="utf8") as f:
  774. while(True):
  775. line = f.readline().strip()
  776. if not line:
  777. break
  778. for i in range(len(line)):
  779. if i==0:
  780. f_w.write(line[i]+" B_company\n")
  781. elif i==len(line)-1:
  782. f_w.write(line[i]+" E_company\n")
  783. f_w.write("\n")
  784. else:
  785. f_w.write(line[i]+" M_company\n")
  786. def addContextToTheEntity(entity_file):
  787. def getContext(file):
  788. list_sent_label = []
  789. with codecs.open(file,"r",encoding="utf8") as f:
  790. sentence = []
  791. while(True):
  792. line = f.readline()
  793. if not line:
  794. break
  795. if len(line)==1:
  796. list_sent_label.append(sentence)
  797. sentence = []
  798. else:
  799. sentence.append([line[0],line.split()[-1].strip()])
  800. return list_sent_label
  801. list_sent_label = getContext("ner_label.txt")
  802. print("getContent done",len(list_sent_label))
  803. context_len = len(list_sent_label)
  804. outputfile = entity_file.split(".")[0]+"_addContext.txt"
  805. with codecs.open(outputfile,"w",encoding="utf8") as f_w:
  806. with codecs.open(entity_file,"r",encoding="utf8") as f_r:
  807. while(True):
  808. entity = f_r.readline().strip()
  809. random_int = np.random.randint(0,context_len)
  810. _sentence = list_sent_label[random_int]
  811. _flag = 0
  812. for item in _sentence:
  813. if _flag==0:
  814. if item[1]=="B_company":
  815. for word_index in range(len(entity)):
  816. if word_index==0:
  817. f_w.write(entity[word_index]+" B_company\n")
  818. elif word_index==len(entity)-1:
  819. f_w.write(entity[word_index]+" E_company\n")
  820. else:
  821. f_w.write(entity[word_index]+" M_company\n")
  822. _flag = 1
  823. else:
  824. f_w.write(item[0]+" "+item[1]+"\n")
  825. elif _flag==1:
  826. if item[1]=="E_company":
  827. _flag = 2
  828. else:
  829. continue
  830. else:
  831. f_w.write(item[0]+" "+item[1]+"\n")
  832. f_w.write("\n")
  833. def makeContext_by_fool_selffool():
  834. '''
  835. @summary: 通过fool和selffool的识别结果来判断一个句子的识别是否正确,若fool和selffool的识别一样,则为正确,否则待定
  836. '''
  837. import psycopg2
  838. conn = psycopg2.connect(dbname="selffool",user="postgres",password="postgres",host="192.168.2.101")
  839. list_filename_text = []
  840. cursor = conn.cursor()
  841. file_index = 0
  842. for file in glob.glob("C:\\Users\\User\\Desktop\\测试数据20190812\\*.html"):
  843. try:
  844. filename = file.split("\\")[-1]
  845. sql = " select count(1) from articles_processed_selffool where id='"+filename+"'"
  846. cursor.execute(sql)
  847. rows = cursor.fetchall()
  848. if rows[0][0]>0:
  849. continue
  850. content = codecs.open(file,"r",encoding="utf8").read()
  851. print(file_index,filename)
  852. text = Preprocessing.segment(Preprocessing.tableToText(BeautifulSoup(content,"lxml")))
  853. _article = Article(id=filename, content=text, sourceContent="", doc_id="", title="")
  854. persistArticle(conn,[_article],"articles_processed_selffool")
  855. list_sentences = []
  856. _sent_index = 0
  857. set_sentences = set()
  858. for x in re.split("[。]", text):
  859. if len(x)>0:
  860. if x in set_sentences:
  861. continue
  862. set_sentences.add(x)
  863. _sentence = Sentences(doc_id=filename,sentence_index=_sent_index,sentence_text=x+"。",tokens=[],pos_tags=[],ner_tags=[])
  864. list_sentences.append(_sentence)
  865. _ner_fool = fool.ner(_sentence.sentence_text)
  866. _ner_selffool = Preprocessing.selffool.ner(_sentence.sentence_text)
  867. if len(set(_ner_fool[0])&set(_ner_selffool[0]))==len(_ner_fool[0]):
  868. table_entity = "entity_mention_selffool"
  869. else:
  870. table_entity = "entity_mention_selffool_notsame"
  871. list_entitys = []
  872. for item in _ner_selffool[0]:
  873. _entity_id = filename+"_"+str(_sent_index)+"_"+str(item[0])+"_"+str(item[1])
  874. _entity = Entity(doc_id=filename,entity_id=_entity_id,entity_text=item[3],entity_type=item[2],sentence_index=_sent_index,begin_index=item[0],end_index=item[1])
  875. list_entitys.append(_entity)
  876. persistEntity(conn,list_entitys,table_entity)
  877. _sent_index += 1
  878. persistSentence(conn,list_sentences,"sentences_selffool")
  879. conn.commit()
  880. except Exception as e:
  881. print(e)
  882. conn.close()
  883. conn = psycopg2.connect(dbname="selffool",user="postgres",password="postgres",host="192.168.2.101")
  884. cursor = conn.cursor()
  885. finally:
  886. file_index += 1
  887. conn.close()
  888. def makeCompare():
  889. '''
  890. @summary: 通过比较fool的多个版本的selffool来判断置信度
  891. '''
  892. bilstm_new = BiLSTM()
  893. path_add = "new_model/"
  894. path = 'model/'+path_add+'model.ckpt'
  895. bilstm_new.restore(path)
  896. conn = psycopg2.connect(dbname="selffool",user="postgres",password="postgres",host="192.168.2.101")
  897. cursor = conn.cursor()
  898. sql = " select doc_id,sentence_index,sentence_text from sentences_selffool A where exists(select 1 from entity_mention_selffool_notsame B where A.doc_id=B.doc_id and A.sentence_index=B.sentence_index and fool_version='selffool') and not exists(select 1 from entity_mention_selffool_notsame B where A.doc_id=B.doc_id and A.sentence_index=B.sentence_index and fool_version='fool') "
  899. cursor.execute(sql)
  900. rows = cursor.fetchall()
  901. table_entity = "entity_mention_selffool_notsame"
  902. _index = 0
  903. try:
  904. for row in rows:
  905. _index += 1
  906. print(_index,len(rows))
  907. doc_id = row[0]
  908. sentence_index = row[1]
  909. '''
  910. sql = " select count(1) from "+table_entity+" where doc_id='"+doc_id+"' and sentence_index="+str(sentence_index)+" and fool_version='fool' "
  911. cursor.execute(sql)
  912. count_rows = cursor.fetchall()
  913. if count_rows[0][0]>0:
  914. continue
  915. '''
  916. text = row[2]
  917. _ner_entity_fool = set()
  918. _ner_entity_selffool = set()
  919. _ner_fool = fool.ner(text)[0]
  920. _ner_selffool = bilstm_new.ner(text)[0]
  921. list_entitys = []
  922. for item in _ner_fool:
  923. _entity_id = doc_id+"_"+str(sentence_index)+"_"+str(item[0])+"_"+str(item[1])
  924. _entity = Entity(doc_id=doc_id,entity_id=_entity_id,entity_text=item[3],entity_type=item[2],sentence_index=sentence_index,begin_index=item[0],end_index=item[1])
  925. list_entitys.append(_entity)
  926. persistEntity(conn,list_entitys,table_entity)
  927. conn.commit()
  928. '''
  929. for item in _ner_fool:
  930. if item[2] in ["org","company"]:
  931. _ner_entity_fool.add(item)
  932. for item in _ner_selffool:
  933. if item[2] in ["org","company"]:
  934. _ner_entity_selffool.add(item)
  935. if len(_ner_entity_fool&_ner_entity_selffool)==len(_ner_entity_fool) and len(_ner_entity_fool)==len(_ner_entity_selffool):
  936. print(text)
  937. print(_ner_selffool)
  938. '''
  939. except Exception as e:
  940. print(e)
  941. conn.close()
  942. conn = psycopg2.connect(dbname="selffool",user="postgres",password="postgres",host="192.168.2.101")
  943. cursor = conn.cursor()
  944. conn.close()
  945. def cluster_difference():
  946. '''
  947. @summary: 对截断的尾部进行聚类
  948. '''
  949. conn = psycopg2.connect(dbname="selffool",user="postgres",password="postgres",host="192.168.2.101")
  950. cursor = conn.cursor()
  951. sql = " select entity_id,doc_id,sentence_index,begin_index,end_index,entity_type,entity_text,fool_version from entity_mention_selffool_notsame where entity_type in ('org','company') order by entity_id "
  952. cursor.execute(sql)
  953. rows = cursor.fetchall()
  954. row_begin = 0
  955. DIFF_LEN = 2
  956. dict_diff_list = dict()
  957. while(row_begin<len(rows)-1):
  958. print(row_begin,len(rows))
  959. doc_id = rows[row_begin][1]
  960. sentence_index = rows[row_begin][2]
  961. row_end = row_begin
  962. for _i in range(row_begin+1,len(rows)):
  963. row_end = _i
  964. if rows[_i][1]==doc_id and rows[_i][2]==sentence_index:
  965. continue
  966. else:
  967. break
  968. list_entitys_fool = []
  969. list_entitys_selffool = []
  970. #对同一篇文章同一个句子的实体进行分类
  971. for _row in rows[row_begin:row_end]:
  972. entity_id = _row[0]
  973. begin_index = _row[3]
  974. end_index = _row[4]-1
  975. entity_type = _row[5]
  976. entity_text = _row[6]
  977. fool_version = _row[7]
  978. if entity_type in ["org","company"]:
  979. _entity = [entity_id,begin_index,end_index,entity_text,entity_type]
  980. if fool_version=="fool":
  981. list_entitys_fool.append(_entity)
  982. else:
  983. list_entitys_selffool.append(_entity)
  984. row_begin = row_end
  985. #分别遍历fool和selffool的结果,对不同点进行聚类
  986. list_key_entityid = []
  987. for _entity_fool in list_entitys_fool:
  988. entity_id_src = _entity_fool[0]
  989. begin_index_src = _entity_fool[1]
  990. end_index_src = _entity_fool[2]
  991. entity_text_src = _entity_fool[3]
  992. entity_type_src = _entity_fool[4]
  993. for _entity_selffool in list_entitys_selffool:
  994. entity_id_des = _entity_selffool[0]
  995. begin_index_des = _entity_selffool[1]
  996. end_index_des = _entity_selffool[2]
  997. entity_text_des = _entity_selffool[3]
  998. entity_type_des = _entity_selffool[4]
  999. if min(end_index_src,end_index_des)>max(begin_index_des,begin_index_src):
  1000. if begin_index_src==begin_index_des:
  1001. _key_begin = "SAME"
  1002. else:
  1003. _key_begin = entity_text_src[0:min(DIFF_LEN,len(entity_text_src))]+"#"+entity_text_des[0:min(DIFF_LEN,len(entity_text_des))]
  1004. if end_index_src==end_index_des:
  1005. _key_end = "SAME"
  1006. else:
  1007. _key_end = entity_text_src[-min(DIFF_LEN,len(entity_text_src)):]+"#"+entity_text_des[-min(DIFF_LEN,len(entity_text_des)):]
  1008. _key = _key_begin+"|"+_key_end
  1009. list_key_entityid.append([_key,[entity_id_src,entity_id_des]])
  1010. #查看是否独有
  1011. for _entity_fool in list_entitys_fool:
  1012. entity_id_src = _entity_fool[0]
  1013. begin_index_src = _entity_fool[1]
  1014. end_index_src = _entity_fool[2]
  1015. entity_text_src = _entity_fool[3]
  1016. entity_type_src = _entity_fool[4]
  1017. find_flag = False
  1018. for item in list_key_entityid:
  1019. if entity_id_src in item[1]:
  1020. find_flag = True
  1021. if not find_flag:
  1022. _key = "fool|"+entity_text_src[-min(DIFF_LEN,len(entity_text_src)):]
  1023. list_key_entityid.append([_key,[entity_id_src]])
  1024. for _entity_fool in list_entitys_selffool:
  1025. entity_id_src = _entity_fool[0]
  1026. begin_index_src = _entity_fool[1]
  1027. end_index_src = _entity_fool[2]
  1028. entity_text_src = _entity_fool[3]
  1029. entity_type_src = _entity_fool[4]
  1030. find_flag = False
  1031. for item in list_key_entityid:
  1032. if entity_id_src in item[1]:
  1033. find_flag = True
  1034. if not find_flag:
  1035. _key = "selffool|"+entity_text_src[-min(DIFF_LEN,len(entity_text_src)):]
  1036. list_key_entityid.append([_key,[entity_id_src]])
  1037. #聚类
  1038. for item in list_key_entityid:
  1039. find_flag = False
  1040. if item[0]=="SAME|SAME":
  1041. continue
  1042. for _key in dict_diff_list.keys():
  1043. if item[0]==_key:
  1044. dict_diff_list[_key].append(item[1])
  1045. find_flag = True
  1046. if not find_flag:
  1047. dict_diff_list[item[0]] = [item[1]]
  1048. print(len(dict_diff_list.keys()))
  1049. list_key_count = []
  1050. for _key in dict_diff_list.keys():
  1051. list_key_count.append([_key,len(dict_diff_list[_key])])
  1052. list_key_count.sort(key=lambda x:x[1],reverse=True)
  1053. with codecs.open("diff_key_count.txt","w",encoding="utf8") as f:
  1054. for item in list_key_count:
  1055. f.write(item[0]+"\t"+str(item[1])+"\n")
  1056. save(dict_diff_list,"dict_diff_list.pk")
  1057. dict_sentence = None
  1058. def get_sentence(doc_id,sentence_index):
  1059. global dict_sentence
  1060. file_dict_sentence = "dict_sentence.pk"
  1061. if dict_sentence is None:
  1062. if os.path.exists(file_dict_sentence):
  1063. dict_sentence = load(file_dict_sentence)
  1064. else:
  1065. conn = psycopg2.connect(dbname="selffool",user="postgres",password="postgres",host="192.168.2.101")
  1066. cursor = conn.cursor()
  1067. sql = " select doc_id,sentence_index,sentence_text from sentences_selffool "
  1068. cursor.execute(sql)
  1069. dict_sentence = dict()
  1070. rows = cursor.fetchall()
  1071. for row in rows:
  1072. _doc_id = row[0]
  1073. _sentence_index = row[1]
  1074. _sentence_text = row[2]
  1075. _key = _doc_id+str(_sentence_index)
  1076. dict_sentence[_key] = _sentence_text
  1077. save(dict_sentence,file_dict_sentence)
  1078. _key = doc_id+str(sentence_index)
  1079. if _key in dict_sentence.keys():
  1080. return dict_sentence[_key]
  1081. return None
  1082. dict_diff_list = None
  1083. def viewEntityByKey():
  1084. global dict_diff_list
  1085. if dict_diff_list is None:
  1086. dict_diff_list = load("dict_diff_list.pk")
  1087. CONTEXT_LEN = 15
  1088. for key in dict_diff_list.keys():
  1089. diff_list = dict_diff_list[key]
  1090. file = "cluster_view/"+re.sub("[\*\|\/\r\n:]","",key.strip())+".xls"
  1091. if os.path.exists(file):
  1092. continue
  1093. list_entityid = []
  1094. list_before = []
  1095. list_center = []
  1096. list_after = []
  1097. list_change = []
  1098. list_type = []
  1099. list_version = []
  1100. if len(diff_list[0])==2:
  1101. for item in diff_list:
  1102. for i in range(len(item)):
  1103. if i==0:
  1104. list_version.append("fool")
  1105. else:
  1106. list_version.append("selffool")
  1107. entityid = item[i]
  1108. split_entityid = entityid.split("html")[1].split("_")
  1109. doc_id = entityid.split("html")[0]+"html"
  1110. sentence_index = split_entityid[1]
  1111. sentence_text = get_sentence(doc_id, sentence_index)
  1112. begin_index = int(split_entityid[2])
  1113. end_index = int(split_entityid[3])-1
  1114. list_entityid.append(entityid)
  1115. before = sentence_text[max(0,begin_index-CONTEXT_LEN):begin_index]
  1116. center = sentence_text[begin_index:end_index]
  1117. after = sentence_text[end_index:min(end_index+CONTEXT_LEN,len(sentence_text))]
  1118. list_before.append(before)
  1119. list_center.append(center)
  1120. list_after.append(after)
  1121. list_change.append(center)
  1122. list_type.append("")
  1123. else:
  1124. version = key.split("|")[0]
  1125. for item in diff_list:
  1126. list_version.append(version)
  1127. entityid = item[0]
  1128. split_entityid = entityid.split("html")[1].split("_")
  1129. doc_id = entityid.split("html")[0]+"html"
  1130. sentence_index = split_entityid[1]
  1131. sentence_text = get_sentence(doc_id, sentence_index)
  1132. begin_index = int(split_entityid[2])
  1133. end_index = int(split_entityid[3])-1
  1134. list_entityid.append(entityid)
  1135. before = sentence_text[max(0,begin_index-CONTEXT_LEN):begin_index]
  1136. center = sentence_text[begin_index:end_index]
  1137. after = sentence_text[end_index:min(end_index+CONTEXT_LEN,len(sentence_text))]
  1138. list_before.append(before)
  1139. list_center.append(center)
  1140. list_after.append(after)
  1141. list_change.append(center)
  1142. list_type.append("")
  1143. data = {"list_entityid":list_entityid,
  1144. "list_before":list_before,
  1145. "list_center":list_center,
  1146. "list_after":list_after,
  1147. "list_change":list_change,
  1148. "list_type":list_type,
  1149. "list_version":list_version}
  1150. df = pd.DataFrame(data,columns=["list_entityid","list_before","list_center","list_after","list_change","list_type","list_version"])
  1151. df.to_excel(file)
  1152. def alterFileByRule(file):
  1153. df = pd.read_excel(file)
  1154. _location = "location"
  1155. for _index in range(len(df["list_entityid"])):
  1156. version = df["list_version"][_index]
  1157. if version=="selffool":
  1158. ''''''
  1159. df["list_change"][_index] = df["list_change"][_index-1]
  1160. df.to_excel(file,columns=["list_entityid","list_before","list_center","list_after","list_change","list_type","list_version"])
  1161. def getCompanyByTianyan():
  1162. token = "b775e2ed-d919-4d5f-8ab1-406d82d6bb56"
  1163. headers = {"Authorization":token}
  1164. url = "http://open.api.tianyancha.com/services/v4/open/searchV2?word="
  1165. _inTianYan = "inTianYan"
  1166. _inSource = "inSource"
  1167. _dict = load("dict_company.pk")
  1168. count = 0
  1169. for entity in load("set_company.pk"):
  1170. try:
  1171. count += 1
  1172. print(count,len(_dict.keys()))
  1173. if entity in _dict:
  1174. _dict[entity][_inSource] = True
  1175. if _dict[entity][_inTianYan]:
  1176. continue
  1177. else:
  1178. _dict[entity] = {_inTianYan:False,_inSource:True}
  1179. r = requests.get(url+entity,headers=headers)
  1180. r_json = r.json()
  1181. if r_json["error_code"]==0:
  1182. for item in r_json["result"]["items"]:
  1183. companyName = re.sub("</?em>","",item["name"]).replace("(","(").replace(")",")")
  1184. if companyName in _dict:
  1185. _dict[companyName][_inTianYan] = True
  1186. else:
  1187. _dict[companyName] = {_inTianYan:True,_inSource:False}
  1188. elif r_json["error_code"]==300007:
  1189. print("剩余次数不足")
  1190. break
  1191. except Exception as e:
  1192. print(str(e))
  1193. save(_dict,"dict_company.pk")
  1194. def labelByTianyan():
  1195. '''
  1196. @summary: 通过天眼查的数据接口来获取标注
  1197. '''
  1198. list_entityid = []
  1199. list_before = []
  1200. list_center = []
  1201. list_after = []
  1202. list_change = []
  1203. list_type = []
  1204. list_version = []
  1205. list_entityid_notmatch = []
  1206. list_before_notmatch = []
  1207. list_center_notmatch = []
  1208. list_after_notmatch = []
  1209. list_change_notmatch = []
  1210. list_type_notmatch = []
  1211. list_version_notmatch = []
  1212. _inTianYan = "inTianYan"
  1213. _inSource = "inSource"
  1214. _dict_company = load("dict_company.pk")
  1215. is_compare = False
  1216. for file in glob.glob("cluster_view/add/*.xls"):
  1217. df = pd.read_excel(file)
  1218. for _index in range(len(df["list_change"])):
  1219. version = df["list_version"][_index]
  1220. if version in ["selffool","fool"]:
  1221. _match_count = 0
  1222. true_entity = None
  1223. if df["list_change"][_index] in _dict_company:
  1224. if _dict_company[df["list_change"][_index]][_inTianYan]:
  1225. _match_count += 1
  1226. true_entity = df["list_change"][_index]
  1227. if is_compare:
  1228. if df["list_change"][_index-1] in _dict_company:
  1229. if _dict_company[df["list_change"][_index-1]][_inTianYan]:
  1230. _match_count += 1
  1231. true_entity = df["list_change"][_index-1]
  1232. if _match_count==1:
  1233. if is_compare:
  1234. list_entityid.append(df["list_entityid"][_index-1])
  1235. list_before.append(df["list_before"][_index-1])
  1236. list_center.append(df["list_center"][_index-1])
  1237. list_after.append(df["list_after"][_index-1])
  1238. list_change.append(df["list_change"][_index-1])
  1239. list_type.append(df["list_type"][_index-1])
  1240. list_version.append(df["list_version"][_index-1])
  1241. list_entityid.append(df["list_entityid"][_index])
  1242. list_before.append(df["list_before"][_index])
  1243. list_center.append(df["list_center"][_index])
  1244. list_after.append(df["list_after"][_index])
  1245. list_change.append(true_entity)
  1246. list_type.append(df["list_type"][_index])
  1247. list_version.append(df["list_version"][_index])
  1248. else:
  1249. if is_compare:
  1250. list_entityid_notmatch.append(df["list_entityid"][_index-1])
  1251. list_before_notmatch.append(df["list_before"][_index-1])
  1252. list_center_notmatch.append(df["list_center"][_index-1])
  1253. list_after_notmatch.append(df["list_after"][_index-1])
  1254. list_change_notmatch.append(df["list_change"][_index-1])
  1255. list_type_notmatch.append(df["list_type"][_index-1])
  1256. list_version_notmatch.append(df["list_version"][_index-1])
  1257. list_entityid_notmatch.append(df["list_entityid"][_index])
  1258. list_before_notmatch.append(df["list_before"][_index])
  1259. list_center_notmatch.append(df["list_center"][_index])
  1260. list_after_notmatch.append(df["list_after"][_index])
  1261. list_change_notmatch.append(df["list_change"][_index])
  1262. list_type_notmatch.append(df["list_type"][_index])
  1263. list_version_notmatch.append(df["list_version"][_index])
  1264. data = {"list_entityid":list_entityid,
  1265. "list_before":list_before,
  1266. "list_center":list_center,
  1267. "list_after":list_after,
  1268. "list_change":list_change,
  1269. "list_type":list_type,
  1270. "list_version":list_version}
  1271. df = pd.DataFrame(data,columns=["list_entityid","list_before","list_center","list_after","list_change","list_type","list_version"])
  1272. df.to_excel("cluster_view/add_match.xls")
  1273. nums = 50000
  1274. _begin = 0
  1275. while(_begin<len(list_entityid_notmatch)):
  1276. data = {"list_entityid":list_entityid_notmatch[_begin:_begin+nums],
  1277. "list_before":list_before_notmatch[_begin:_begin+nums],
  1278. "list_center":list_center_notmatch[_begin:_begin+nums],
  1279. "list_after":list_after_notmatch[_begin:_begin+nums],
  1280. "list_change":list_change_notmatch[_begin:_begin+nums],
  1281. "list_type":list_type_notmatch[_begin:_begin+nums],
  1282. "list_version":list_version_notmatch[_begin:_begin+nums]}
  1283. df = pd.DataFrame(data,columns=["list_entityid","list_before","list_center","list_after","list_change","list_type","list_version"])
  1284. df.to_excel("cluster_view/add_notmatch_"+str(_begin)+".xls")
  1285. _begin += nums
  1286. def cluster_entitys():
  1287. '''
  1288. @summary: 对实体进行聚类,统一截断
  1289. '''
  1290. tail_pattern = re.compile("学校|[大中小]学校?|医院|公司|分公司|研究院|政府采购中心|学院|中心校?|办公室|政府|财[政务]局|办事处|委员会|[部总支]队|警卫局|幼儿园|党委|党校|银行|分行|解放军|发电厂|供电局|管理所|供电公司|卷烟厂|机务段|研究[院所]|油厂|调查局|调查中心|出版社|电视台|监狱|水厂|服务站|信用合作联社|信用社|交易所|交易中心|交易中心党校|科学院|测绘所|运输厅|管理处|局|中心|机关|部门?|处|科|厂|集团|图书馆|馆|所|厅|楼|区|酒店|场|基地|矿|餐厅|酒店")
  1291. dict_tail_entitys = {}
  1292. listfile = ["cluster_view/*_match.xls","cluster_view/done/*.xls","cluster_view/tofix/done/*.xls"]
  1293. count = 0
  1294. for globfile in listfile:
  1295. for file in glob.glob(globfile):
  1296. isadd = re.search("fool|add",file) is not None
  1297. count += 1
  1298. print(count,file)
  1299. df = pd.read_excel(file)
  1300. list_entityid = df["list_entityid"]
  1301. list_before = df["list_before"]
  1302. list_center = df["list_center"]
  1303. list_after = df["list_after"]
  1304. list_change = df["list_change"]
  1305. list_type = df["list_type"]
  1306. list_version = df["list_version"]
  1307. for _index in range(len(list_entityid)):
  1308. '''
  1309. #跳过标注为1的
  1310. if str(list_change[_index])=="1":
  1311. continue
  1312. '''
  1313. #跳过用于对比标注的fool数据
  1314. if not isadd and list_version[_index]=="fool":
  1315. continue
  1316. if str(list_change[_index])=="1":
  1317. _key = "-1-"
  1318. else:
  1319. _find = re.findall(tail_pattern,str(list_change[_index]))
  1320. if len(_find)==0:
  1321. _key = "other"
  1322. else:
  1323. _key = "-".join(_find)
  1324. if _key in dict_tail_entitys:
  1325. dict_tail_entitys[_key]["list_entityid"].append(list_entityid[_index])
  1326. dict_tail_entitys[_key]["list_before"].append(list_before[_index])
  1327. dict_tail_entitys[_key]["list_center"].append(list_center[_index])
  1328. dict_tail_entitys[_key]["list_after"].append(list_after[_index])
  1329. dict_tail_entitys[_key]["list_change"].append(list_change[_index])
  1330. dict_tail_entitys[_key]["list_type"].append(list_type[_index])
  1331. dict_tail_entitys[_key]["list_version"].append(list_version[_index])
  1332. else:
  1333. dict_tail_entitys[_key] = {"list_entityid":[list_entityid[_index]],
  1334. "list_before":[list_before[_index]],
  1335. "list_center":[list_center[_index]],
  1336. "list_after":[list_after[_index]],
  1337. "list_change":[list_change[_index]],
  1338. "list_type":[list_type[_index]],
  1339. "list_version":[list_version[_index]]}
  1340. print(len(dict_tail_entitys.keys()))
  1341. for _key in dict_tail_entitys.keys():
  1342. filename = "cluster_view/cluster/"+_key+".xls"
  1343. nums = 50000
  1344. _begin = 0
  1345. if os.path.exists(filename):
  1346. continue
  1347. while(_begin*nums<len(dict_tail_entitys[_key]["list_entityid"])):
  1348. data = {"list_entityid":dict_tail_entitys[_key]["list_entityid"][_begin*nums:(_begin+1)*nums],
  1349. "list_before":dict_tail_entitys[_key]["list_before"][_begin*nums:(_begin+1)*nums],
  1350. "list_center":dict_tail_entitys[_key]["list_center"][_begin*nums:(_begin+1)*nums],
  1351. "list_after":dict_tail_entitys[_key]["list_after"][_begin*nums:(_begin+1)*nums],
  1352. "list_change":dict_tail_entitys[_key]["list_change"][_begin*nums:(_begin+1)*nums],
  1353. "list_type":dict_tail_entitys[_key]["list_type"][_begin*nums:(_begin+1)*nums],
  1354. "list_version":dict_tail_entitys[_key]["list_version"][_begin*nums:(_begin+1)*nums]}
  1355. df = pd.DataFrame(data,columns=["list_entityid","list_before","list_center","list_after","list_change","list_type","list_version"])
  1356. df.to_excel("cluster_view/cluster/"+_key+"-"+str(_begin)+".xls")
  1357. _begin += 1
  1358. def tofix():
  1359. '''
  1360. @summary: 获取所有待标注数据,使用规则过滤掉一些,再均分
  1361. '''
  1362. conn = psycopg2.connect(dbname="selffool",user="postgres",password="postgres",host="192.168.2.101")
  1363. cursor = conn.cursor()
  1364. sql = " select entity_id,fool_version,entity_text from entity_mention_selffool_notsame"
  1365. cursor.execute(sql)
  1366. dict_idversion_entity = {}
  1367. rows = cursor.fetchall()
  1368. for row in rows:
  1369. entity_id = row[0]
  1370. fool_version = row[1]
  1371. entity_text = row[2]
  1372. _key = entity_id+"-"+fool_version
  1373. dict_idversion_entity[_key] = entity_text
  1374. list_entityid_tofix = []
  1375. list_before_tofix = []
  1376. list_center_tofix = []
  1377. list_after_tofix = []
  1378. list_change_tofix = []
  1379. list_type_tofix = []
  1380. list_version_tofix = []
  1381. list_entityid_nottofix = []
  1382. list_before_nottofix = []
  1383. list_center_nottofix = []
  1384. list_after_nottofix = []
  1385. list_change_nottofix = []
  1386. list_type_nottofix = []
  1387. list_version_nottofix = []
  1388. nottofix_pattern = "^[A-Za-z0-9\-]*[省市区县州镇]|^[A-Za-z0-9\-]+$"
  1389. listfile = ["cluster_view/*notmatch*.xls"]
  1390. count = 0
  1391. data = []
  1392. for globfile in listfile:
  1393. for file in glob.glob(globfile):
  1394. isadd = re.search("fool|add",file) is not None
  1395. count += 1
  1396. print(count)
  1397. df = pd.read_excel(file)
  1398. list_entityid = df["list_entityid"]
  1399. list_before = df["list_before"]
  1400. list_center = df["list_center"]
  1401. list_after = df["list_after"]
  1402. list_change = df["list_change"]
  1403. list_type = df["list_type"]
  1404. list_version = df["list_version"]
  1405. for _index in range(len(list_entityid)):
  1406. if not isadd and list_version[_index]=="fool":
  1407. continue
  1408. _key = str(list_entityid[_index])+"-"+str(list_version[_index])
  1409. if _key in dict_idversion_entity and dict_idversion_entity[_key]!=list_center[_index]:
  1410. list_center[_index] = dict_idversion_entity[_key]
  1411. list_change[_index] = dict_idversion_entity[_key]
  1412. data.append([str(list_entityid[_index]),str(list_before[_index]),str(list_center[_index]),str(list_after[_index]),str(list_change[_index]),str(list_type[_index]),str(list_version[_index])])
  1413. data.sort(key=lambda x:x[4])
  1414. for item in data:
  1415. entityid = item[0]
  1416. before = item[1]
  1417. center = item[2]
  1418. after = item[3]
  1419. change = item[4]
  1420. type = item[5]
  1421. version = item[6]
  1422. if re.search(nottofix_pattern,change) is not None:
  1423. list_entityid_nottofix.append(entityid)
  1424. list_before_nottofix.append(before)
  1425. list_center_nottofix.append(center)
  1426. list_after_nottofix.append(after)
  1427. list_change_nottofix.append(change)
  1428. list_type_nottofix.append(type)
  1429. list_version_nottofix.append(version)
  1430. else:
  1431. list_entityid_tofix.append(entityid)
  1432. list_before_tofix.append(before)
  1433. list_center_tofix.append(center)
  1434. list_after_tofix.append(after)
  1435. list_change_tofix.append(change)
  1436. list_type_tofix.append(type)
  1437. list_version_tofix.append(version)
  1438. parts = 16
  1439. nums = len(list_entityid_tofix)//parts
  1440. _begin = 0
  1441. while(_begin*nums<len(list_entityid_tofix)):
  1442. data = {"list_entityid":list_entityid_tofix[_begin*nums:(_begin+1)*nums],
  1443. "list_before":list_before_tofix[_begin*nums:(_begin+1)*nums],
  1444. "list_center":list_center_tofix[_begin*nums:(_begin+1)*nums],
  1445. "list_after":list_after_tofix[_begin*nums:(_begin+1)*nums],
  1446. "list_change":list_change_tofix[_begin*nums:(_begin+1)*nums],
  1447. "list_type":list_type_tofix[_begin*nums:(_begin+1)*nums],
  1448. "list_version":list_version_tofix[_begin*nums:(_begin+1)*nums]}
  1449. df = pd.DataFrame(data,columns=["list_entityid","list_before","list_center","list_after","list_change","list_type","list_version"])
  1450. df.to_excel("cluster_view/tofix/"+str(_begin)+".xls")
  1451. _begin += 1
  1452. data = {"list_entityid":list_entityid_nottofix,
  1453. "list_before":list_before_nottofix,
  1454. "list_center":list_center_nottofix,
  1455. "list_after":list_after_nottofix,
  1456. "list_change":list_change_nottofix,
  1457. "list_type":list_type_nottofix,
  1458. "list_version":list_version_nottofix}
  1459. df = pd.DataFrame(data,columns=["list_entityid","list_before","list_center","list_after","list_change","list_type","list_version"])
  1460. df.to_excel("cluster_view/tofix/nottofix.xls")
  1461. def updateEntityview():
  1462. '''
  1463. @summary: 将视图中的数据更新回去,以selffool的为准进行更新操作,若是遇到fool新增的,则进行插入操作,fool_version改为selffool_add
  1464. '''
  1465. conn = psycopg2.connect(dbname="selffool",user="postgres",password="postgres",host="192.168.2.101")
  1466. cursor = conn.cursor()
  1467. listfile = ["cluster_view/cluster/*.xls"]
  1468. count = 0
  1469. for globfile in listfile:
  1470. for file in glob.glob(globfile):
  1471. count += 1
  1472. print(count,file)
  1473. df = pd.read_excel(file)
  1474. for _index in range(len(df["list_entityid"])):
  1475. entity_id = df["list_entityid"][_index]
  1476. doc_id = entity_id.split("html")[0]+"html"
  1477. list_index = entity_id.split("html")[1].split("_")
  1478. sentence_index = list_index[1]
  1479. begin_index = list_index[2]
  1480. end_index = list_index[3]
  1481. change = str(df["list_change"][_index])
  1482. type = str(df["list_type"][_index])
  1483. version = str(df["list_version"][_index])
  1484. if version=="fool":
  1485. sql = " update entity_mention_selffool_notsame set new_text='"+str(change)+"',new_type='"+type+"',fool_version='fool_add' where entity_id='"+entity_id+"' and fool_version='fool' "
  1486. cursor.execute(sql)
  1487. else:
  1488. sql = " update entity_mention_selffool_notsame set new_text='"+str(change)+"',new_type='"+type+"' where entity_id='"+entity_id+"' and fool_version='selffool' "
  1489. cursor.execute(sql)
  1490. conn.commit()
  1491. conn.close()
  1492. def makeLabelText():
  1493. '''
  1494. @summary: 更新数据太慢,直接从数据库查询出数据库进行替换,然后生成训练数据
  1495. '''
  1496. conn = psycopg2.connect(dbname="selffool",user="postgres",password="postgres",host="192.168.2.101")
  1497. cursor = conn.cursor()
  1498. #根据聚类的结果生成替换字典
  1499. dict_replace = dict()
  1500. listfile = ["cluster_view/cluster/*.xls"]
  1501. count = 0
  1502. for globfile in listfile:
  1503. for file in glob.glob(globfile):
  1504. count += 1
  1505. print(count,file)
  1506. df = pd.read_excel(file)
  1507. for _index in range(len(df["list_entityid"])):
  1508. entity_id = df["list_entityid"][_index]
  1509. doc_id = entity_id.split("html")[0]+"html"
  1510. list_index = entity_id.split("html")[1].split("_")
  1511. sentence_index = list_index[1]
  1512. begin_index = list_index[2]
  1513. end_index = list_index[3]
  1514. change = str(df["list_change"][_index])
  1515. type = str(df["list_type"][_index])
  1516. version = str(df["list_version"][_index])
  1517. _key = entity_id+version
  1518. dict_replace[_key] = [change,type]
  1519. print("get dict_replace done")
  1520. #从数据库中查询出实体,按照entity_id排序
  1521. data_entity = []
  1522. sql = " select entity_id,doc_id,sentence_index,entity_text,entity_type,'selffool' from entity_mention_selffool order by entity_id "
  1523. cursor.execute(sql)
  1524. rows = cursor.fetchall()
  1525. data_entity = data_entity+rows
  1526. sql = " select entity_id,doc_id,sentence_index,entity_text,entity_type,fool_version from entity_mention_selffool_notsame order by entity_id "
  1527. cursor.execute(sql)
  1528. rows = cursor.fetchall()
  1529. data_entity = data_entity+rows
  1530. #生成doc_id-sentence_index-list_entity_type字典
  1531. dict_sent_entitys = dict()
  1532. _begin = 0
  1533. while(_begin<len(data_entity)-1):
  1534. _begin_doc_id = data_entity[_begin][1]
  1535. _begin_sentence_index = data_entity[_begin][2]
  1536. _end = _begin
  1537. print(_begin)
  1538. for end in range(_begin+1,len(data_entity)):
  1539. _end = end
  1540. _end_doc_id = data_entity[end][1]
  1541. _end_sentence_index = data_entity[end][2]
  1542. if _begin_doc_id==_end_doc_id and _begin_sentence_index==_end_sentence_index:
  1543. continue
  1544. else:
  1545. break
  1546. for item in data_entity[_begin:_end]:
  1547. entity_id = item[0]
  1548. doc_id = item[1]
  1549. sentence_index = item[2]
  1550. entity_text = item[3]
  1551. entity_type = item[4]
  1552. version = item[5]
  1553. _key = doc_id+"-"+str(sentence_index)
  1554. if _key not in dict_sent_entitys:
  1555. dict_sent_entitys[_key] = []
  1556. #进行替换
  1557. if entity_type in ["org","company"]:
  1558. _key1 = entity_id+version
  1559. if _key1 in dict_replace:
  1560. if str(dict_replace[_key1][0])=="1":
  1561. continue
  1562. if dict_replace[_key1][1] in ["org","company","person","location"]:
  1563. for item in re.split("##",dict_replace[_key1][0]):
  1564. dict_sent_entitys[_key].append([item,dict_replace[_key1][1]])
  1565. else:
  1566. for item in re.split("##",dict_replace[_key1][0]):
  1567. dict_sent_entitys[_key].append([item,entity_type])
  1568. else:
  1569. if version=="selffool":
  1570. dict_sent_entitys[_key].append([entity_text,entity_type])
  1571. else:
  1572. dict_sent_entitys[_key].append([entity_text,entity_type])
  1573. _begin = _end
  1574. print("get dict_sent_entitys done")
  1575. #查询出句子
  1576. sql = " select doc_id,sentence_index,sentence_text from sentences_selffool order by doc_id "
  1577. cursor.execute(sql)
  1578. list_sentence = cursor.fetchall()
  1579. count = 0
  1580. with codecs.open("selffool_train.txt","w",encoding="utf8") as f:
  1581. for sent in list_sentence:
  1582. count += 1
  1583. print(count)
  1584. _key = sent[0]+"-"+str(sent[1])
  1585. sentence = sent[2]
  1586. if len(sentence)>2000:
  1587. continue
  1588. if _key in dict_sent_entitys:
  1589. data_item,_find_flag = makeLabel(sentence, dict_sent_entitys[_key])
  1590. for _word,_label in data_item:
  1591. f.write(_word+" "+_label+"\n")
  1592. else:
  1593. if np.random.random()>0.8:
  1594. data_item,_find_flag = makeLabel(sentence, [])
  1595. for _word,_label in data_item:
  1596. f.write(_word+" "+_label+"\n")
  1597. f.write("\n")
  1598. f.flush()
  1599. if __name__=="__main__":
  1600. #makeFoolTrainData()
  1601. #makeTrainTxt()
  1602. #labelEntity()
  1603. #readlabeldata("cleanedEntity.txt",getContext("ner_train.txt"))
  1604. #makeDict_filename_content()
  1605. #selectByRule()
  1606. #updateLabel()
  1607. #importLabelData()
  1608. #makeCertainEntity()
  1609. #addContextToTheEntity("company_found.tsv")
  1610. #makeContext_by_fool_selffool()
  1611. #makeCompare()
  1612. #cluster_difference()
  1613. #viewEntityByKey()
  1614. #alterFileByRule("cluster_view/change/SAME版社#大学.xls")
  1615. #getCompanyByTianyan()
  1616. '''
  1617. data = load("dict_company.pk")
  1618. for item in data.keys():
  1619. print(item,data[item])
  1620. '''
  1621. #labelByTianyan()
  1622. '''
  1623. token = "b775e2ed-d919-4d5f-8ab1-406d82d6bb56"
  1624. headers = {"Authorization":token}
  1625. url = "http://open.api.tianyancha.com/services/v4/open/searchV2?word="
  1626. r = requests.get(url+"安阳鑫龙煤业(集团)龙山煤业有限责任公司",headers=headers)
  1627. r_json = r.json()
  1628. print(r_json)
  1629. '''
  1630. #tofix()
  1631. cluster_entitys()
  1632. makeLabelText()