forked from brockholzer/DeepEHR
-
Notifications
You must be signed in to change notification settings - Fork 1
/
negex.py
executable file
·220 lines (180 loc) · 8.79 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
import re
def sortRules (ruleList):
"""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. """
ruleList.sort(key = len, reverse = True)
sortedList = []
for rule in ruleList:
s = rule.strip()
s= s.split('\t')
splitTrig = s[0].split()
trig = r'\s+'.join(splitTrig)
pattern = r'\b(' + trig + r')\b'
s.append(re.compile(pattern, re.IGNORECASE))
sortedList.append(s)
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)