1 # ====================================================================
2 # Licensed under the Apache License, Version 2.0 (the "License");
3 # you may not use this file except in compliance with the License.
4 # You may obtain a copy of the License at
6 # http://www.apache.org/licenses/LICENSE-2.0
8 # Unless required by applicable law or agreed to in writing, software
9 # distributed under the License is distributed on an "AS IS" BASIS,
10 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 # See the License for the specific language governing permissions and
12 # limitations under the License.
13 # ====================================================================
15 from lucene import Token, PythonTokenFilter, TermAttribute
16 from lia.analysis.AnalyzerUtils import AnalyzerUtils
19 # A TokenFilter extension
22 class SynonymFilter(PythonTokenFilter):
23 TOKEN_TYPE_SYNONYM = "SYNONYM"
25 def __init__(self, inStream, engine):
26 super(SynonymFilter, self).__init__(inStream)
28 self.synonymStack = []
29 self.termAttr = self.addAttribute(TermAttribute.class_)
30 self.save = inStream.cloneAttributes()
32 self.inStream = inStream
34 def incrementToken(self):
36 if len(self.synonymStack) > 0:
37 syn = self.synonymStack.pop()
38 self.restoreState(syn)
41 if not self.inStream.incrementToken():
44 self.addAliasesToStack()
48 def addAliasesToStack(self):
50 synonyms = self.engine.getSynonyms(self.termAttr.term())
54 current = self.captureState()
56 for synonym in synonyms:
57 self.save.restoreState(current)
58 AnalyzerUtils.setTerm(self.save, synonym)
59 AnalyzerUtils.setType(self.save, self.TOKEN_TYPE_SYNONYM)
60 AnalyzerUtils.setPositionIncrement(self.save, 0)
61 self.synonymStack.append(self.save.captureState())