import os import random from collections import OrderedDict import pickle import json import click T_Q_MAP = {"PER":"人名 是 什么","LOC":"地址 是 什么","ORG":"机构 是 什么"} T_T2_MAP = {"PER":"nr","LOC":"ns","ORG":"nt"} @click.command() @click.option('--inputfile', default='baike_sents_full.jsonl') @click.option('--outputdir', default="../") @click.option('--datatype', default="Train") @click.option("--triefile") def get_ner(inputfile, outputdir, datatype, triefile): use4squad = True use4iob = True use4nrst = True trie = pickle.load(open(triefile, 'rb')) squad_file = open(os.path.join(outputdir, datatype+"-squad.json"),'w') if use4squad else None iob_file = open(os.path.join(outputdir, datatype+"-iob.txt"),'w') if use4iob else None nrst_file = open(os.path.join(outputdir, datatype+"-nrst.txt"),'w') if use4nrst else None root = {} squad_list = [] iob_list = [] nrst_list = [] id_count = 0 with open(inputfile, 'r') as fn: for line in fn: content = json.loads(line) sentence = ''.join(content["sentence"].strip().split()) sentId = content["sentId"] sent_len = len(sentence) used_list = [] wordtype = {} for Type in ["PER","LOC","ORG"]: idx = 0;rev_idx = sent_len-1 i_e_list = [] while idx < sent_len: idx, entity_span = get_entity(sentence, idx,sent_len, Type, trie) i_e_list.append(entity_span) while rev_idx >= 0: rev_idx, entity_span = rev_get_entity(sentence, rev_idx, sent_len, Type, trie) i_e_list.append(entity_span) for entity_span in i_e_list: flag = 1 e_len = len(entity_span) if e_len > 1: for s in used_list: jiaoji = entity_span.intersection(s) if len(jiaoji) > 1: if e_len < len(s) or jiaoji == s: flag = 0 else: used_list.remove(s) if flag: used_list.append(entity_span) wordtype[tuple(entity_span)] = Type if len(used_list) == 0: continue id_count+=1 print(id_count) if use4squad: article = SquadFormat(sentence, used_list, wordtype, id_count) squad_list.append(article) if use4iob: iob_sent = iobFormat(sentence, used_list, wordtype, id_count) iob_list.append(iob_sent+'\n') if use4nrst: nrst_sent = nrstFormat(sentence, used_list,wordtype, id_count) nrst_list.append(nrst_sent+'\n') if use4squad: random.shuffle(squad_list) root["data"] = squad_list json.dump(root, squad_file) if use4iob: random.shuffle(iob_list) for sent in iob_list: iob_file.write(sent) iob_file.close() if use4nrst: random.shuffle(nrst_list) for sent in nrst_list: nrst_file.write(sent) nrst_file.close() def SquadFormat(sentence, used_list, wordtype, id_count): type2answers = {"PER":[], "LOC":[], "ORG":[]} qas = [] paragraphs = [] article = {} for span in used_list: Type = wordtype[tuple(span)] begin = min(span) end = max(span)+1 entity = ' '.join(sentence[begin:end]) start = begin+begin+2 #whitespace offset type2answers[Type].append({"text":entity,"answer_start":start}) for Type in type2answers.keys(): question = T_Q_MAP[Type] if(type2answers[Type] == []): type2answers[Type].append({"text":'#',"answer_start":0}) qas.append({'question':question, 'id':("%024d")%id_count, "answers":type2answers[Type]}) context = '# ' + ' '.join(sentence) paragraphs.append({"context":context, "qas":qas}) article["title"] = " " article["paragraphs"] = paragraphs return article def nrstFormat(sentence, used_list, wordtype, id_count): sentence = [char+'/o' for char in sentence] for span in used_list: Type = T_T2_MAP[wordtype[tuple(span)]] for i in span: sentence[i] = sentence[i].replace('/o',"/"+Type) return ' '.join(sentence) def iobFormat(sentence, used_list, wordtype, id_count): sentence = [char+'/O' for char in sentence] for span in used_list: Type = wordtype[tuple(span)] span_start = min(span) sentence[span_start] = sentence[span_start].replace("/O", '/B-'+Type) for i in span-set([span_start]): sentence[i] = sentence[i].replace('/O', "/I-"+Type) return ' '.join(sentence) def get_entity(sentence, idx, sent_len,Type, trie): origin_idx = idx root_node = trie[Type] node = root_node while(idx < sent_len and sentence[idx] in node): node = node[sentence[idx]] idx += 1 if node != root_node and '/-/-' in node: return idx, set(range(origin_idx, idx)) else: return origin_idx+1, set() def rev_get_entity(sentence,idx, sent_len, Type, trie): origin_idx = idx root_node = trie["rev_"+Type] node = root_node while(idx >= 0 and sentence[idx] in node): node = node[sentence[idx]] idx -= 1 if(node != root_node and '/-/-' in node ): return idx, set(range(idx+1, origin_idx+1)) return origin_idx-1, set() if __name__ == "__main__": get_ner()