Commit ce4a6430 by hxw

update

parent 7abfc697
import pickle
import click
import json
import tqdm
from collections import OrderedDict
Trie = pickle.load(open('Trie.data','rb'))
@click.command()
@click.option('--file_name',default='baike_sents_full.jsonl')
def get_ner(file_name):
wf = open("test.jsonl",'w')
with open(file_name,'r') as data:
for line in data:
content = json.loads(line)
sentence = ''.join(content["sentence"].strip().split())
sentId = content["sentId"]
sent_len = len(sentence)
ner_list = []
used_idx = set()
used_list = []
wordtype = {}
NamedEntity = []
for Type in ["PER","LOC","ORG"]:
idx = 0;rev_idx = sent_len-1
i_w_list = []
while(idx < sent_len ):
[idx,word_used_idx] = get_entity(sentence,idx,sent_len,Type)
i_w_list.append([idx,word_used_idx])
while(rev_idx >= 0):
[rev_idx,word_used_idx] = rev_get_entity(sentence,rev_idx,sent_len,Type)
i_w_list.append([idx,word_used_idx])
for idx,word_used_idx in i_w_list:
flag = 1
if(len(word_used_idx) > 1):
for s in used_list:
jiaoji = word_used_idx.intersection(s)
if(jiaoji != set()):
if( len(word_used_idx) < len(s) or jiaoji == s):
flag = 0
else:
used_list.remove(s)
if(flag):
used_list.append(word_used_idx)
wordtype[tuple(word_used_idx)] = Type
for s in used_list:
Type = wordtype[tuple(s)]
begin = min(s)
end = max(s)+1
entity = sentence[begin:end]
NamedEntity.append(OrderedDict([("Text",entity),("Begin",begin),("Type",Type)]))
wf.write(json.dumps(OrderedDict([("SentId",sentId),("Sentence",sentence),("NamedEntity",NamedEntity)]))+'\n')
def get_entity(sentence,idx,sent_len,Type):
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):
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))]
else:
return [origin_idx-1,set()]
if __name__ == "__main__":
get_ner()
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment