-
Notifications
You must be signed in to change notification settings - Fork 0
/
coreNlpUtil.py
332 lines (241 loc) · 13 KB
/
coreNlpUtil.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
from parsedSentencesLoader import ParsedSentencesLoader
from word import Word
def parseText(sentences):
loader = ParsedSentencesLoader()
parseResult = loader.load(sentences)
if len(parseResult['sentences']) == 1:
return parseResult
wordOffset = 0
for i in xrange(len(parseResult['sentences'])):
if i>0:
for j in xrange(len(parseResult['sentences'][i]['dependencies'])):
for k in xrange(1,3):
tokens = parseResult['sentences'][i]['dependencies'][j][k].split('-')
if tokens[0] == 'ROOT':
newWordIndex = 0
else:
if not tokens[len(tokens)-1].isdigit(): # forced to do this because of entries like u"lost-8'" in parseResult
continue
newWordIndex = int(tokens[len(tokens)-1])+wordOffset
if len(tokens) == 2:
parseResult['sentences'][i]['dependencies'][j][k] = tokens[0]+ '-' + str(newWordIndex)
else:
w = ''
for l in xrange(len(tokens)-1):
w += tokens[l]
if l < len(tokens)-2:
w += '-'
parseResult['sentences'][i]['dependencies'][j][k] = w + '-' + str(newWordIndex)
wordOffset += len(parseResult['sentences'][i]['words'])
# merge information of all sentences into one
for i in xrange(1,len(parseResult['sentences'])):
parseResult['sentences'][0]['text'] += ' ' + parseResult['sentences'][i]['text']
for jtem in parseResult['sentences'][i]['dependencies']:
parseResult['sentences'][0]['dependencies'].append(jtem)
for jtem in parseResult['sentences'][i]['words']:
parseResult['sentences'][0]['words'].append(jtem)
# remove all but the first entry
parseResult['sentences'] = parseResult['sentences'][0:1]
return parseResult
##############################################################################################################################
##############################################################################################################################
def nerWordAnnotator(parseResult):
res = []
wordIndex = 1
for i in xrange(len(parseResult['sentences'][0]['words'])):
tag = [[parseResult['sentences'][0]['words'][i][1]['CharacterOffsetBegin'], parseResult['sentences'][0]['words'][i][1]['CharacterOffsetEnd']], wordIndex, parseResult['sentences'][0]['words'][i][0], parseResult['sentences'][0]['words'][i][1]['NamedEntityTag']]
wordIndex += 1
if tag[3] <> 'O':
res.append(tag)
return res
##############################################################################################################################
##############################################################################################################################
def ner(parseResult):
nerWordAnnotations = nerWordAnnotator(parseResult)
namedEntities = []
currentNE = []
currentCharacterOffsets = []
currentWordOffsets = []
for i in xrange(len(nerWordAnnotations)):
if i == 0:
currentNE.append(nerWordAnnotations[i][2])
currentCharacterOffsets.append(nerWordAnnotations[i][0])
currentWordOffsets.append(nerWordAnnotations[i][1])
if len(nerWordAnnotations) == 1:
namedEntities.append([currentCharacterOffsets, currentWordOffsets, currentNE, nerWordAnnotations[i-1][3]])
break
continue
if nerWordAnnotations[i][3] == nerWordAnnotations[i-1][3] and nerWordAnnotations[i][1] == nerWordAnnotations[i-1][1]+1:
currentNE.append(nerWordAnnotations[i][2])
currentCharacterOffsets.append(nerWordAnnotations[i][0])
currentWordOffsets.append(nerWordAnnotations[i][1])
if i == len(nerWordAnnotations)-1:
namedEntities.append([currentCharacterOffsets, currentWordOffsets, currentNE, nerWordAnnotations[i][3]])
else:
namedEntities.append([currentCharacterOffsets, currentWordOffsets, currentNE, nerWordAnnotations[i-1][3]])
currentNE = [nerWordAnnotations[i][2]]
currentCharacterOffsets = []
currentCharacterOffsets.append(nerWordAnnotations[i][0])
currentWordOffsets = []
currentWordOffsets.append(nerWordAnnotations[i][1])
if i == len(nerWordAnnotations)-1:
namedEntities.append([currentCharacterOffsets, currentWordOffsets, currentNE, nerWordAnnotations[i][3]])
#print namedEntities
return namedEntities
##############################################################################################################################
##############################################################################################################################
def posTag(parseResult):
res = []
wordIndex = 1
for i in xrange(len(parseResult['sentences'][0]['words'])):
tag = [[parseResult['sentences'][0]['words'][i][1]['CharacterOffsetBegin'], parseResult['sentences'][0]['words'][i][1]['CharacterOffsetEnd']], wordIndex, parseResult['sentences'][0]['words'][i][0], parseResult['sentences'][0]['words'][i][1]['PartOfSpeech']]
wordIndex += 1
res.append(tag)
return res
##############################################################################################################################
##############################################################################################################################
def lemmatize(parseResult):
res = []
wordIndex = 1
for i in xrange(len(parseResult['sentences'][0]['words'])):
tag = [[parseResult['sentences'][0]['words'][i][1]['CharacterOffsetBegin'], parseResult['sentences'][0]['words'][i][1]['CharacterOffsetEnd']], wordIndex, parseResult['sentences'][0]['words'][i][0], parseResult['sentences'][0]['words'][i][1]['Lemma']]
wordIndex += 1
res.append(tag)
return res
def prepareSentence(sentence):
sentenceParseResult = parseText(sentence)
sentenceLemmatized = lemmatize(sentenceParseResult)
sentencePosTagged = posTag(sentenceParseResult)
sentenceLemmasAndPosTags = []
for i in xrange(len(sentenceLemmatized)):
sentenceLemmasAndPosTags.append([])
for i in xrange(len(sentenceLemmatized)):
for item in sentenceLemmatized[i]:
sentenceLemmasAndPosTags[i].append(item)
sentenceLemmasAndPosTags[i].append(sentencePosTagged[i][3])
return sentenceLemmasAndPosTags
def prepareSentence2(sentence):
sentenceParseResult = parseText(sentence)
sentenceLemmatized = lemmatize(sentenceParseResult)
sentencePosTagged = posTag(sentenceParseResult)
sentenceLemmasAndPosTags = []
for i in xrange(len(sentenceLemmatized)):
sentenceLemmasAndPosTags.append([])
for i in xrange(len(sentenceLemmatized)):
for item in sentenceLemmatized[i]:
sentenceLemmasAndPosTags[i].append(item)
sentenceLemmasAndPosTags[i].append(sentencePosTagged[i][3])
words = []
for rawWord in sentenceLemmasAndPosTags:
words.append(Word(rawWord[1] - 1, rawWord[2], rawWord[3], rawWord[4], ''))
return words
def dependencyParseAndPutOffsets(parseResult):
# returns dependency parse of the sentence whhere each item is of the form (rel, left{charStartOffset, charEndOffset, wordNumber}, right{charStartOffset, charEndOffset, wordNumber})
dParse = parseResult['sentences'][0]['dependencies']
words = parseResult['sentences'][0]['words']
#for item in dParse:
#print item
result = []
for item in dParse:
newItem = []
# copy 'rel'
newItem.append(item[0])
# construct and append entry for 'left'
left = item[1][0:item[1].rindex("-")]
wordNumber = item[1][item[1].rindex("-")+1:]
if wordNumber.isdigit() == False:
continue
left += '{' + words[int(wordNumber)-1][1]['CharacterOffsetBegin'] + ' ' + words[int(wordNumber)-1][1]['CharacterOffsetEnd'] + ' ' + wordNumber + '}'
newItem.append(left)
# construct and append entry for 'right'
right = item[2][0:item[2].rindex("-")]
wordNumber = item[2][item[2].rindex("-")+1:]
if wordNumber.isdigit() == False:
continue
right += '{' + words[int(wordNumber)-1][1]['CharacterOffsetBegin'] + ' ' + words[int(wordNumber)-1][1]['CharacterOffsetEnd'] + ' ' + wordNumber + '}'
newItem.append(right)
result.append(newItem)
return result
##############################################################################################################################
##############################################################################################################################
def findParents(dependencyParse, wordIndex, word):
# word index assumed to be starting at 1
# the third parameter is needed because of the collapsed representation of the dependencies...
wordsWithIndices = ((int(item[2].split('{')[1].split('}')[0].split(' ')[2]), item[2].split('{')[0]) for item in dependencyParse)
wordsWithIndices = list(set(wordsWithIndices))
wordsWithIndices = sorted(wordsWithIndices, key=lambda item: item[0])
wordIndexPresentInTheList = False
for item in wordsWithIndices:
if item[0] == wordIndex:
wordIndexPresentInTheList = True
break
parentsWithRelation = []
if wordIndexPresentInTheList:
for item in dependencyParse:
currentIndex = int(item[2].split('{')[1].split('}')[0].split(' ')[2])
if currentIndex == wordIndex:
parentsWithRelation.append([int(item[1].split('{')[1].split('}')[0].split(' ')[2]), item[1].split('{')[0], item[0]])
else:
# find the closest following word index which is in the list
nextIndex = 0
for i in xrange(len(wordsWithIndices)):
if wordsWithIndices[i][0] > wordIndex:
nextIndex = wordsWithIndices[i][0]
break
if nextIndex == 0:
return [] #?
for i in xrange(len(dependencyParse)):
if int(dependencyParse[i][2].split('{')[1].split('}')[0].split(' ')[2]) == nextIndex:
pos = i
break
for i in xrange(pos, len(dependencyParse)):
try:
if '_' in dependencyParse[i][0] and word in dependencyParse[i][0]:
parent = [int(dependencyParse[i][1].split('{')[1].split('}')[0].split(' ')[2]), dependencyParse[i][1].split('{')[0], dependencyParse[i][0]]
parentsWithRelation.append(parent)
break
except:
break
return parentsWithRelation
##############################################################################################################################
##############################################################################################################################
def findChildren(dependencyParse, wordIndex, word):
# word index assumed to be starting at 1
# the third parameter is needed because of the collapsed representation of the dependencies...
wordsWithIndices = ((int(item[2].split('{')[1].split('}')[0].split(' ')[2]), item[2].split('{')[0]) for item in dependencyParse)
wordsWithIndices = list(set(wordsWithIndices))
wordsWithIndices = sorted(wordsWithIndices, key=lambda item: item[0])
wordIndexPresentInTheList = False
for item in wordsWithIndices:
if item[0] == wordIndex:
wordIndexPresentInTheList = True
break
childrenWithRelation = []
if wordIndexPresentInTheList:
#print True
for item in dependencyParse:
currentIndex = int(item[1].split('{')[1].split('}')[0].split(' ')[2])
if currentIndex == wordIndex:
childrenWithRelation.append([int(item[2].split('{')[1].split('}')[0].split(' ')[2]), item[2].split('{')[0], item[0]])
else:
# find the closest following word index which is in the list
nextIndex = 0
for i in xrange(len(wordsWithIndices)):
if wordsWithIndices[i][0] > wordIndex:
nextIndex = wordsWithIndices[i][0]
break
if nextIndex == 0:
return []
for i in xrange(len(dependencyParse)):
if int(dependencyParse[i][2].split('{')[1].split('}')[0].split(' ')[2]) == nextIndex:
pos = i
break
for i in xrange(pos, len(dependencyParse)):
try:
if '_' in dependencyParse[i][0] and word in dependencyParse[i][0]:
child = [int(dependencyParse[i][2].split('{')[1].split('}')[0].split(' ')[2]), dependencyParse[i][2].split('{')[0], dependencyParse[i][0]]
childrenWithRelation.append(child)
break
except:
break
return childrenWithRelation