forked from mongoose54/negex
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathnegex.py
304 lines (242 loc) · 10.8 KB
/
negex.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
# -*- coding: UTF-8 -*-
import re
import csv
from typing import List
def easyNg(trigPath: str, reprtPath: str, outPath: str, checkResults: bool = False) -> None:
"""Apply the negex to the specified report file using the specified triggers file and saves the result on the specified output file
trigPath should be the path to the triggers file
reprtPath should be the path to the report file
outPath should be the path to the output file
"""
# Open files
# Rules
irules = sortRules(open(trigPath, "r").readlines())
# Reports
reports = csv.reader(open(reprtPath, 'r'), delimiter='\t')
next(reports) # Skips the header row of reports
# Output
outFile = open(
outPath, 'w')
# Initial setup for variables
reportNum = 0
correctNum = 0
output = []
outputfile = csv.writer(outFile, delimiter='\t')
correctReports = []
# Negex Implementation
for report in reports:
tagger = negTagger(sentence=report[2], phrases=[
report[1]], rules=irules, negP=False)
report.append(tagger.getNegTaggedSentence())
report.append(tagger.getNegationFlag())
report += tagger.getScopes()
reportNum += 1
output.append(report)
# Check accuracy (if enabled)
if checkResults:
if report[3].lower() == report[5]:
correctNum += 1
correctReports.append(reportNum)
if checkResults:
outputfile.writerow(
['Percentage correct:', float(correctNum)/float(reportNum)])
outputfile.writerow(["Correct: " + str(correctReports)])
# Save output
for row in output:
if row:
outputfile.writerow(row)
outFile.close()
def sortRules(ruleList: List[str]):
"""Return sorted list of rules.
Rules should be in a tab-delimited format: 'rule\t\t[four letter negation tag]'
Sorts list of rules descending based on length of the rule,
splits each rule into components, converts pattern to regular expression,
and appends it to the end of the rule. """
# Sort the list by length, from greatest to smallest
ruleList.sort(key=len, reverse=True)
sortedList = []
# Formats the triggers using regex and save them into sortedList
for rule in ruleList:
cleanList = rule.strip().split('\t') # Cleanup trigger and split at tab
splitTrig = cleanList[0].split()
trig = r'\s+'.join(splitTrig)
pattern = r'\b(' + trig + r')\b'
cleanList.append(re.compile(pattern, re.IGNORECASE))
sortedList.append(cleanList)
return sortedList
class negTagger(object):
'''Take a sentence and tag negation terms and negated phrases.
Keyword arguments:
sentence -- string to be tagged
phrases -- list of phrases to check for negation
rules -- list of negation trigger terms from the sortRules function
negP -- tag 'possible' terms as well (default = True) '''
def __init__(self, sentence='', phrases=None, rules=None,
negP=True):
self.__sentence = sentence
self.__phrases = phrases
self.__rules = rules
self.__negTaggedSentence = ''
self.__scopesToReturn = []
self.__negationFlag = None
filler = '_'
for rule in self.__rules:
reformatRule = re.sub(r'\s+', filler, rule[0].strip())
self.__sentence = rule[3].sub(' ' + rule[2].strip()
+ reformatRule
+ rule[2].strip() + ' ', self.__sentence)
for phrase in self.__phrases:
phrase = re.sub(r'([.^$*+?{\\|()[\]])', r'\\\1', phrase)
splitPhrase = phrase.split()
joiner = r'\W+'
joinedPattern = r'\b' + joiner.join(splitPhrase) + r'\b'
reP = re.compile(joinedPattern, re.IGNORECASE)
m = reP.search(self.__sentence)
if m:
self.__sentence = self.__sentence.replace(m.group(0), '[PHRASE]'
+ re.sub(r'\s+', filler, m.group(0).strip())
+ '[PHRASE]')
# Exchanges the [PHRASE] ... [PHRASE] tags for [NEGATED] ... [NEGATED]
# based on PREN, POST rules and if negPoss is set to True then based on
# PREP and POSP, as well.
# Because PRENEGATION [PREN} is checked first it takes precedent over
# POSTNEGATION [POST]. Similarly POSTNEGATION [POST] takes precedent over
# POSSIBLE PRENEGATION [PREP] and [PREP] takes precedent over POSSIBLE
# POSTNEGATION [POSP].
overlapFlag = 0
prenFlag = 0
postFlag = 0
prePossibleFlag = 0
postPossibleFlag = 0
sentenceTokens = self.__sentence.split()
sentencePortion = ''
aScopes = []
sb = []
# check for [PREN]
for i in range(len(sentenceTokens)):
if sentenceTokens[i][:6] == '[PREN]':
prenFlag = 1
overlapFlag = 0
if sentenceTokens[i][:6] in ['[CONJ]', '[PSEU]', '[POST]', '[PREP]', '[POSP]']:
overlapFlag = 1
if i+1 < len(sentenceTokens):
if sentenceTokens[i+1][:6] == '[PREN]':
overlapFlag = 1
if sentencePortion.strip():
aScopes.append(sentencePortion.strip())
sentencePortion = ''
if prenFlag == 1 and overlapFlag == 0:
sentenceTokens[i] = sentenceTokens[i].replace(
'[PHRASE]', '[NEGATED]')
sentencePortion = sentencePortion + ' ' + sentenceTokens[i]
sb.append(sentenceTokens[i])
if sentencePortion.strip():
aScopes.append(sentencePortion.strip())
sentencePortion = ''
sb.reverse()
sentenceTokens = sb
sb2 = []
# Check for [POST]
for i in range(len(sentenceTokens)):
if sentenceTokens[i][:6] == '[POST]':
postFlag = 1
overlapFlag = 0
if sentenceTokens[i][:6] in ['[CONJ]', '[PSEU]', '[PREN]', '[PREP]', '[POSP]']:
overlapFlag = 1
if i+1 < len(sentenceTokens):
if sentenceTokens[i+1][:6] == '[POST]':
overlapFlag = 1
if sentencePortion.strip():
aScopes.append(sentencePortion.strip())
sentencePortion = ''
if postFlag == 1 and overlapFlag == 0:
sentenceTokens[i] = sentenceTokens[i].replace(
'[PHRASE]', '[NEGATED]')
sentencePortion = sentenceTokens[i] + ' ' + sentencePortion
sb2.insert(0, sentenceTokens[i])
if sentencePortion.strip():
aScopes.append(sentencePortion.strip())
sentencePortion = ''
self.__negTaggedSentence = ' '.join(sb2)
if negP:
sentenceTokens = sb2
sb3 = []
# Check for [PREP]
for i in range(len(sentenceTokens)):
if sentenceTokens[i][:6] == '[PREP]':
prePossibleFlag = 1
overlapFlag = 0
if sentenceTokens[i][:6] in ['[CONJ]', '[PSEU]', '[POST]', '[PREN]', '[POSP]']:
overlapFlag = 1
if i+1 < len(sentenceTokens):
if sentenceTokens[i+1][:6] == '[PREP]':
overlapFlag = 1
if sentencePortion.strip():
aScopes.append(sentencePortion.strip())
sentencePortion = ''
if prePossibleFlag == 1 and overlapFlag == 0:
sentenceTokens[i] = sentenceTokens[i].replace(
'[PHRASE]', '[POSSIBLE]')
sentencePortion = sentencePortion + ' ' + sentenceTokens[i]
sb3 = sb3 + ' ' + sentenceTokens[i]
if sentencePortion.strip():
aScopes.append(sentencePortion.strip())
sentencePortion = ''
sb3.reverse()
sentenceTokens = sb3
sb4 = []
# Check for [POSP]
for i in range(len(sentenceTokens)):
if sentenceTokens[i][:6] == '[POSP]':
postPossibleFlag = 1
overlapFlag = 0
if sentenceTokens[i][:6] in ['[CONJ]', '[PSEU]', '[PREN]', '[PREP]', '[POST]']:
overlapFlag = 1
if i+1 < len(sentenceTokens):
if sentenceTokens[i+1][:6] == '[POSP]':
overlapFlag = 1
if sentencePortion.strip():
aScopes.append(sentencePortion.strip())
sentencePortion = ''
if postPossibleFlag == 1 and overlapFlag == 0:
sentenceTokens[i] = sentenceTokens[i].replace(
'[PHRASE]', '[POSSIBLE]')
sentencePortion = sentenceTokens[i] + ' ' + sentencePortion
sb4.insert(0, sentenceTokens[i])
if sentencePortion.strip():
aScopes.append(sentencePortion.strip())
self.__negTaggedSentence = ' '.join(sb4)
if '[NEGATED]' in self.__negTaggedSentence:
self.__negationFlag = 'negated'
elif '[POSSIBLE]' in self.__negTaggedSentence:
self.__negationFlag = 'possible'
else:
self.__negationFlag = 'affirmed'
self.__negTaggedSentence = self.__negTaggedSentence.replace(
filler, ' ')
for line in aScopes:
tokensToReturn = []
thisLineTokens = line.split()
for token in thisLineTokens:
if token[:6] not in ['[PREN]', '[PREP]', '[POST]', '[POSP]']:
tokensToReturn.append(token)
self.__scopesToReturn.append(' '.join(tokensToReturn))
def getNegTaggedSentence(self):
return self.__negTaggedSentence
def getNegationFlag(self):
return self.__negationFlag
def getScopes(self):
return self.__scopesToReturn
def __str__(self):
text = self.__negTaggedSentence
text += '\t' + self.__negationFlag
text += '\t' + '\t'.join(self.__scopesToReturn)
# Interactive mode if not module
if __name__ == "__main__":
# easyNg(input("\nPath dos Triggers:\n"), input(
# "\nPath dos reports:\n"), input("\nPath do output:\n"))
# print('Digite os paths para:')
# easyNg(input('Triggers:\n'), input('Reports:\n'), input('Output:\n'), input(
# 'O seu arquivo de reports contém conteúdo para verificação? '))
easyNg('demo/triggers.txt', 'demo/reports.txt', 'demo/output.txt', True)
print("\n \nPronto! Abra o arquivo de output para ver os resultados.")