import re
import json
# a input document of sentences
document="These are oranges and apples and and pears, but not pinapples\nThese are oranges and apples and pears, but not pinapples"
# uncomment to test UNICODE
document="तुम मुझे दोस्त कहते कहते हो"
sentences=[] # sentences
seen = {} # map if a token has been see already!
# split into sentences
lines=document.splitlines()
for index,line in enumerate(lines):
print("Line:%d %s" % (index,line))
# split token that are words
# LP: (for Simon ;P we do not care of punct at all!
rgx = re.compile("([\w][\w']*\w)")
tokens=rgx.findall(line)
# uncomment to test UNICODE
tokens=["तुम","मुझे","दोस्त","कहते","कहते","हो"]
print("Tokens:",tokens)
sentence={} # a sentence
items=[] # word tokens
# for each token word
for index_word,word in enumerate(tokens):
# uncomment to test UNICODE
my_regex = r"(?<!\S){}(?!\S)".format(re.escape(word))
#my_regex = r"\b(?=\w)" + re.escape(word) + r"\b(?!\w)"
r = re.compile(my_regex, flags=re.I | re.X | re.UNICODE)
item = {}
# for each matched token in sentence
for m in r.finditer(document):
token=m.group()
characterOffsetBegin=m.start()
characterOffsetEnd=characterOffsetBegin+len(m.group()) - 1 # LP: star from 0
print ("word:%s characterOffsetBegin:%d characterOffsetEnd:%d" % (token, characterOffsetBegin, characterOffsetEnd) )
found=-1
if word in seen:
found=seen[word]
if characterOffsetBegin > found:
# store last word has been seen
seen[word] = characterOffsetBegin
item['index']=index_word+1 #// word index starts from 1
item['word']=token
item['characterOffsetBegin'] = characterOffsetBegin;
item['characterOffsetEnd'] = characterOffsetEnd;
items.append(item)
break
sentence['text']=line
sentence['tokens']=items
sentences.append(sentence)
print(json.dumps(sentences, indent=4, sort_keys=True))
print("------ testing ------")
text=''
for sentence in sentences:
for token in sentence['tokens']:
# LP: we get the token from a slice in original text
text = text + document[token['characterOffsetBegin']:token['characterOffsetEnd']+1] + " "
text = text + '\n'
print(text)