From 3f98cdd85a4ead5614c14547844eef72aa286a20 Mon Sep 17 00:00:00 2001 From: hxw Date: Fri, 4 May 2018 10:24:57 +0800 Subject: [PATCH] ner --- generate_3sents.py | 208 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ generate_sents.py | 174 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 382 insertions(+) create mode 100644 generate_3sents.py create mode 100644 generate_sents.py diff --git a/generate_3sents.py b/generate_3sents.py new file mode 100644 index 0000000..b0e9a37 --- /dev/null +++ b/generate_3sents.py @@ -0,0 +1,208 @@ +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") +@click.option('--vocfile') +def get_ner(inputfile, outputdir, datatype, triefile,vocfile): + 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 + type2voc = get_voc(vocfile) + with open(inputfile, 'r') as fn: + for line in fn: + print ('k') + 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) + if len(entity_span) > 1: + i_e_list.append(entity_span) + while rev_idx >= 0: + rev_idx, entity_span = rev_get_entity(sentence, rev_idx, sent_len, Type, trie) + if len(entity_span) > 1: + i_e_list.append(entity_span) + for entity_span in i_e_list : + flag = 1 + e_len = len(entity_span) + 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 + for i in range(3): + sentence = replace_word(sentence,used_list,wordtype,type2voc) + 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 get_voc(vocfile): + type2voc = {"PER":{},"ORG":{},"LOC":{}} + with open(vocfile,'r') as vocf: + for line in vocf: + try: + word,w_type = line.strip().split(' -- ') + except ValueError: + continue + length = len(word) + if length in type2voc[w_type]: + type2voc[w_type][length].add(word) + else: + type2voc[w_type][length] = set() + type2voc[w_type][length].add(word) + return type2voc + +def replace_word(sentence, used_list, wordtype, type2voc): + for span in used_list: + Type = wordtype[tuple(span)] + begin = min(span) + end = max(span)+1 + entity = sentence[begin:end] + length = len(entity) + slice = random.sample(type2voc[Type][length],1)[0] + sentence = sentence.replace(entity,slice) + return sentence + +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() diff --git a/generate_sents.py b/generate_sents.py new file mode 100644 index 0000000..522c371 --- /dev/null +++ b/generate_sents.py @@ -0,0 +1,174 @@ +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) + if len(entity_span) > 1: + i_e_list.append(entity_span) + while rev_idx >= 0: + rev_idx, entity_span = rev_get_entity(sentence, rev_idx, sent_len, Type, trie) + if len(entity_span) > 1: + i_e_list.append(entity_span) + + for entity_span in i_e_list: + flag = 1 + + for s in used_list: + jiaoji = entity_span.intersection(s) + if len(jiaoji) > 1: + if len(entity_span) < 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() -- libgit2 0.27.1