-
Notifications
You must be signed in to change notification settings - Fork 0
/
phraseSearch.py
220 lines (201 loc) · 7.89 KB
/
phraseSearch.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
#!/usr/bin/env python
# -*- coding:utf-8
# vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4
import sys
import json
import codecs
from etool import args, logs
from datetime import datetime
from unidecode import unidecode
__processor__ = 'PhraseFilter'
logger = None
phraseList = []
phraseConf = []
def generatePhraseList(phraseStrArray):
'''Convert input phrases to internal Phrase format.'''
for ph in phraseStrArray:
parts = unicode(unidecode(ph.strip())).split('\t')
if len(parts) == 2:
conf = float(parts[1])
else:
conf = 0.5
phrase = eval(parts[0])
if not(type(phrase[-1]) == int or type(phrase[-1]) == float):
phrase.append(3) # Default minDistance Value
phraseList.append(phrase)
phraseConf.append(conf)
def getPhrase(phraseStr):
global phraseList, phraseConf
phraseList = phraseStr
phraseConf = [0]*len(phraseList)
def filterByPhrase(sentence, order=True):
'''Check for presence of phrases'''
#phrasesPresent = [(k, [[token[0] for token in enumerate(sentence[0]) if kl[0] == token[1][kl[1]]] for kl in k[0:-1]]) for k in phraseList]
phrasePresent = False
for phrase in phraseList:
#raw_input('next - %s' % phrase)
minDistance = phrase[-1]
sLen = len(sentence[0])
distance = 0
i = 0
lastPos = 0
flag = False
if order:
wordSeen = []
wordNotSeen = phrase[1:-1]
wordReq = phrase[0]
while i < sLen:
word = sentence[0][i]
if flag:
break
if unicode(word[wordReq[1]]) == unicode(wordReq[0]):
if len(wordReq) == 3:
if word['POS'] != wordReq[2]:
i += 1
continue
if lastPos == 0:
lastPos = i
wordSeen.append(wordReq)
if wordNotSeen:
wordReq = wordNotSeen[0]
wordNotSeen.remove(wordReq)
else:
distance = i - lastPos
if distance < minDistance:
lastPos = i
wordSeen.append(wordReq)
if wordNotSeen != []:
wordReq = wordNotSeen[0]
wordNotSeen.remove(wordReq)
else:
lastPos = 0
wordSeen = []
wordReq = phrase[0]
wordNotSeen = phrase[1:-1]
elif any([k for k in wordSeen if unicode(k[0]) == unicode(word[k[1]])]) or any([k for k in wordNotSeen if unicode(k[0]) == unicode(word[k[1]])]):
wordSeen = []
wordNotSeen = phrase[1:-1]
wordReq = phrase[0]
if wordSeen == phrase[0:-1]:
flag = True
i += 1
if flag:
return (phrase, i)
else:
wordSeen = []
wordNotSeen = phrase[0:-1]
#wordReq = phrase[0]
while i < sLen:
word = sentence[0][i]
nextWord = [k for k in phrase[0:-1] if unicode(k[0]) == unicode(word[k[1]])]
if len(k) == 3:
if word['POS'] != k[2]:
nextWord == []
if nextWord == []:
i += 1
continue
i += 1
if nextWord[0] in wordSeen:
distance = 0
wordSeen = []
wordNotSeen = phrase[0:-1]
continue
else:
wordSeen.append(nextWord[0])
wordNotSeen.remove(nextWord[0])
if len(wordSeen) == 1:
distance = 0
lastPos = i
else:
newDist = i - lastPos
if newDist > minDistance:
wordSeen = nextWord
wordNotSeen = phrase[0:-1]
wordNotSeen.remove(nextWord[0])
distance = 0
lastPos = i
else:
if newDist > distance:
distance = newDist
lastPos = i
if wordNotSeen == []:
phrasePresent = True
break
if phrasePresent:
phrasePresent = False
return (phrase, i) # i is the offset of phrase within sentence
return (False, None)
def phraseSearch(reader, writer):
'''Loop through input articles and output articles containing the phrase'''
jLoads = json.loads
jDumps = json.dumps
write = writer.write
flush = writer.flush
j = 0
for line in reader:
j += 1
article = unidecode(line)
try:
articleJson = jLoads(unidecode(article))
except ValueError:
logger.debug("unable to load json line number %s" % j)
continue
tokens = articleJson['BasisEnrichment']['tokens']
sOffsets = [k[0] for k in enumerate(tokens) if k[1]['POS'] == 'SENT']
sOffsets.insert(0, 0)
sOffsets.append(len(tokens) - 1)
sentences = [[tokens[sOffsets[i]:sOffsets[i + 1]]] for i in range(0, len(sOffsets) - 1)]
results = map(filterByPhrase, sentences)
if any([k for k, v in results]):
offSets = [sOffsets[offs] + k[1] for offs, k in enumerate(results) if k[0] is not False]
#print "results %s " % offSets
results = [k[0] for k in results if k[0] is not False]
articleJson['phrasesPresent'] = {"phrases": results, "offsets": offSets,
"conf": [phraseConf[phraseList.index(k)] for k in results]}
write(jDumps(articleJson))
write('\n')
flush()
return None
def main():
ap = args.get_parser()
ap.add_argument('-i', '--input', default='sys.stdin', type=str, help='Path to the input file.'
'Default is sys.stdin')
ap.add_argument('-o', '--out', default='sys.stdout', type=str, help='Path to the output file.'
'Default is sys.stdout')
ap.add_argument('searchPhrase', default='config/phrases.txt', type=str, help='Path to '
'the Phrase File if "-f" flag is specified, else the input string is considered'
'to be the phrase.')
ap.add_argument('-f', '--file', action='store_true', default=False, help='If given, then the '
'the searchPhrase argument is interpreted as path to a file')
global logger
logger = logs.getLogger("%s-%s.log" % (__processor__, str(datetime.now())))
arg = ap.parse_args()
logs.init(args)
inputFile = None
outFile = None
phraseFile = None
if arg.input == 'sys.stdin':
reader = codecs.getreader('utf-8')(sys.stdin)
else:
inputFile = open(arg.input, "r")
reader = codecs.getreader('utf-8')(inputFile)
if arg.out == 'sys.stdout':
writer = codecs.getwriter('utf-8')(sys.stdout)
else:
outFile = codecs.open(arg.out, "w", encoding="utf-8")
writer = codecs.getwriter('utf-8')(outFile)
if arg.file:
phraseFile = codecs.open(arg.searchPhrase, encoding='utf-8')
generatePhraseList(phraseFile.readlines())
else:
generatePhraseList([arg.searchPhrase])
phraseSearch(reader, writer)
#close all files
if inputFile:
inputFile.close()
if outFile:
outFile.close()
if phraseFile:
phraseFile.close()
if __name__ == "__main__":
main()