add --shared
[pylucene.git] / lucene-java-3.4.0 / lucene / contrib / spellchecker / src / java / org / apache / lucene / search / suggest / FileDictionary.java
1 package org.apache.lucene.search.suggest;
2
3 /**
4  * Licensed to the Apache Software Foundation (ASF) under one or more
5  * contributor license agreements.  See the NOTICE file distributed with
6  * this work for additional information regarding copyright ownership.
7  * The ASF licenses this file to You under the Apache License, Version 2.0
8  * (the "License"); you may not use this file except in compliance with
9  * the License.  You may obtain a copy of the License at
10  *
11  *     http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  */
19
20
21 import java.io.*;
22
23 import org.apache.lucene.search.spell.Dictionary;
24 import org.apache.lucene.search.spell.TermFreqIterator;
25
26
27 /**
28  * Dictionary represented by a text file.
29  * 
30  * <p/>Format allowed: 1 string per line, optionally with a tab-separated integer value:<br/>
31  * word1 TAB 100<br/>
32  * word2 word3 TAB 101<br/>
33  * word4 word5 TAB 102<br/>
34  */
35 public class FileDictionary implements Dictionary {
36
37   private BufferedReader in;
38   private String line;
39   private boolean hasNextCalled;
40
41   public FileDictionary(InputStream dictFile) {
42     in = new BufferedReader(new InputStreamReader(dictFile));
43   }
44
45   /**
46    * Creates a dictionary based on a reader.
47    */
48   public FileDictionary(Reader reader) {
49     in = new BufferedReader(reader);
50   }
51
52   public TermFreqIterator getWordsIterator() {
53     return new fileIterator();
54   }
55
56   final class fileIterator implements TermFreqIterator {
57     private float curFreq;
58     
59     public String next() {
60       if (!hasNextCalled) {
61         hasNext();
62       }
63       hasNextCalled = false;
64       return line;
65     }
66     
67     public float freq() {
68       return curFreq;
69     }
70
71     public boolean hasNext() {
72       hasNextCalled = true;
73       try {
74         line = in.readLine();
75         if (line != null) {
76           String[] fields = line.split("\t");
77           if (fields.length > 1) {
78             curFreq = Float.parseFloat(fields[1]);
79             line = fields[0];
80           } else {
81             curFreq = 1;
82           }
83         }
84       } catch (IOException ex) {
85         throw new RuntimeException(ex);
86       }
87       return (line != null) ? true : false;
88     }
89
90     public void remove() {
91       throw new UnsupportedOperationException();
92     }
93   }
94
95 }