PyLucene 3.4.0-1 import
[pylucene.git] / samples / LuceneInAction / lia / tools / T9er.py
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
5 #
6 #       http://www.apache.org/licenses/LICENSE-2.0
7 #
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 # ====================================================================
14
15 from lucene import \
16      WhitespaceAnalyzer, Document, Field, IndexReader, IndexWriter
17
18
19 class T9er(object):
20
21     keys = [         "2abc", "3def",
22             "4ghi",  "5jkl", "6mno",
23             "7pqrs", "8tuv", "9wxyz"]
24
25     keyMap = {}
26
27     def main(cls, argv):
28         
29         if len(argv) != 3:
30             print "Usage: T9er <WordNet index dir> <t9 index>"
31             return
32         
33         for key in cls.keys:
34             c = key[0]
35             k = key[1:]
36             for kc in k:
37                 cls.keyMap[kc] = c
38                 print kc, "=", c
39
40         indexDir = argv[1]
41         t9dir = argv[2]
42
43         reader = IndexReader.open(indexDir)
44
45         numDocs = reader.maxDoc()
46         print "Processing", numDocs, "words"
47
48         writer = IndexWriter(t9dir, WhitespaceAnalyzer(), True)
49
50         for id in xrange(reader.maxDoc()):
51             origDoc = reader.document(id)
52             word = origDoc.get("word")
53             if word is None or len(word) == 0:
54                 continue
55
56             newDoc = Document()
57             newDoc.add(Field("word", word,
58                              Field.Store.YES, Field.Index.UN_TOKENIZED))
59             newDoc.add(Field("t9", cls.t9(word),
60                              Field.Store.YES, Field.Index.UN_TOKENIZED))
61             newDoc.add(Field("length", str(len(word)),
62                              Field.Store.NO, Field.Index.UN_TOKENIZED))
63             writer.addDocument(newDoc)
64             if id % 100 == 0:
65                 print "Document", id
66
67         writer.optimize()
68         writer.close()
69
70         reader.close()
71
72     def t9(cls, word):
73
74         return ''.join([cls.keyMap[c] for c in word])
75
76     main = classmethod(main)
77     t9 = classmethod(t9)